본문 바로가기

C

c++ leetcode 290 word pattern with double hashmap(100% faster) solution

code >>

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
35
36
class Solution {
public:
    bool wordPattern(string pattern, string s) {
        
        int pSize = (int)pattern.size();
        int sSize = (int)s.size();
        istringstream ss(s);
        vector<string> saveVector;
        string stringBuffer;
        
        unordered_map<charstring> hashmap;
        unordered_map<stringchar> twohashmap;
        
        
        while (getline(ss, stringBuffer, ' '))
        {
            saveVector.push_back(stringBuffer);
        }
 
        if (pSize != saveVector.size())
            return false;
        for (int i = 0; i < pSize; i++)
        {
            if ((hashmap.count(pattern[i]) == 0&& (twohashmap.count(saveVector[i]) == 0))
            {
                hashmap[pattern[i]] = saveVector[i];
                twohashmap[saveVector[i]] = pattern[i];
            }
            else
                if ((hashmap[pattern[i]] != saveVector[i]) && (twohashmap[saveVector[i]] != pattern[i]))
                    return false;
        }
 
        return true;
    }
};