Scribbling

[C++] istringstream 본문

Computer Science/C++

[C++] istringstream

focalpoint 2023. 8. 22. 03:20

 

 LeetCode 290. Word Pattern

https://leetcode.com/problems/word-pattern/

 

Word Pattern - LeetCode

Can you solve this real interview question? Word Pattern - Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.   Example

leetcode.com

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        unordered_map<char, string> patternMap;
        unordered_set<string> wordSet;
        istringstream iss(s);
        int i = 0, n = pattern.length();
        for (string word; iss >> word; i++) {
            if (i == n)
                return false;
            char p = pattern[i];
            if (patternMap.find(p) == patternMap.end()) {
                if (wordSet.find(word) == wordSet.end()) {
                    patternMap[p] = word;
                    wordSet.insert(word);
                }
                else {
                    return false;
                }
            }
            else {
                if (word != patternMap[p]) {
                    return false;
                }
            }
        }
        return i == n;
    }
};

'Computer Science > C++' 카테고리의 다른 글

[C++] ostringstream, isdigit  (0) 2023.08.29
[C++] to_string, deque, string split  (0) 2023.08.24
[C++] Chapter 2: Types  (0) 2023.08.21
[C++] Load Balancing  (0) 2023.08.19
[C++] lower_bound, upper_bound  (0) 2023.08.18