Home LeetCode - 290. Word Pattern
Post
Cancel

LeetCode - 290. Word Pattern

290. Word Pattern - easy

문제

Given a pattern and a string str, find if str 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 str.

제한사항

  • You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space

입출력 예

1
2
3
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
1
2
3
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
1
2
3
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
1
2
3
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false

풀이

  • hash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        vector<string> strVec;
        string token;
        stringstream ss(str);
        
        while (getline(ss, token, ' ')) {
		    strVec.push_back(token);
	    }
        
        map<char, string> m;
        set<string> s;
        
        if(pattern.size() != strVec.size())
            return false;
        
        for(auto i = 0 ; i < pattern.size() ; ++i){
            if(m.find(pattern[i]) != m.end()){
                if(m[pattern[i]] != strVec[i])
                    return false;
            }
            else{
                m[pattern[i]] = strVec[i];
                s.insert(m[pattern[i]]);
            }
        }
        
        if(s.size() == m.size())
            return true;
        else
            return false;
    }
};
This post is licensed under CC BY 4.0 by the author.