290. Word Pattern

2018-09-24  本文已影响0人  SilentDawn

Problem

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.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

Example

Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Input: pattern = "abba", str = "dog dog dog dog"
Output: false

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        vector<string> temp_vec;
        stringstream ss(str);
        string temp;
        while(ss>>temp)
            temp_vec.push_back(temp);
        if(pattern.size()!=temp_vec.size())
            return false;
        map<char,string> forward;
        map<string,char> backward;
        for(int i=0;i<pattern.size();i++){
            if(forward.find(pattern[i])==forward.end()&&backward.find(temp_vec[i])==backward.end()){
                forward[pattern[i]] = temp_vec[i];
                backward[temp_vec[i]] = pattern[i];
            }else{
                if(forward[pattern[i]]==temp_vec[i] && backward[forward[pattern[i]]]==pattern[i]){
                    continue;
                }
                else{
                    return false;
                }
            }
        }
        return true;
    }
};

Result

290.Word Pattern.png
上一篇 下一篇

猜你喜欢

热点阅读