Skip to content

Latest commit

 

History

History
70 lines (62 loc) · 2.48 KB

290. Word Pattern.md

File metadata and controls

70 lines (62 loc) · 2.48 KB

思路

类似205. Isomorphic Strings, 所以解题思路基本一样。
将pattern和str中个每个元素都用一个数代替,这个数代表了该元素是第几个出现的(如 "abba" -> 1221, "dog cat cat dog" -> 1221), 则结果应该是一样的。 为了记录是否出现过,pattern用一个长度为26的数组实现,str用map来实现,此外还用一个count计数。

更新:

可以用istringstream很方便地将str按照空格分开。

C++

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        map<string, int>mp;
        vector<int>vc(26, 0);
        string sub_str;
        int count = 1, pos = 0, pre; // pos记录空格的下一个位置,pre为上一个空格位置的下一个位置
        for(int i = 0; i < pattern.size(); i++){
            if(pos >= str.size()) return false; // str中元素少于pattern中的元素
            pre = pos;
            while(str[pos] != ' ' && pos < str.size()) pos++; // 此时pos为空格的位置或str结束位置
            // s.substr(pos1,n)返回字符串s从pos1开始n个字符组成的串
            sub_str = str.substr(pre, pos - pre);
            pos++; // pos记录空格的下一个位置
            
            // 以下代码基本同205题
            if(vc[pattern[i] - 'a'] != mp[sub_str]) return false;
            if(vc[pattern[i] - 'a'] == 0){
                vc[pattern[i] - 'a'] = count;
                mp[sub_str] = count++;
            } 
        }
        if(pos != str.size() + 1) return false; // str中元素多余pattern中的元素
        return true;
    }
};

更新:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        unordered_map<char, int>c_mp;
        vector<int>c2int;
        unordered_map<string, int>str_mp;
                
        int count = 0;
        for(char c: pattern){
            if(c_mp.find(c) == c_mp.end()) c_mp[c] = count++;
            c2int.push_back(c_mp[c]);
        }
        
        count = 0;
        int i = 0;
        string cur;
        istringstream iss(str);
        while(iss.good()){ // or !iss.eof()
            iss >> cur;
            if(str_mp.find(cur) == str_mp.end()) str_mp[cur] = count++;
            if(i >= c2int.size() || c2int[i] != str_mp[cur]) return false;
            i++;
        }
        
        return i == c2int.size();
    }
};