leetcode 290 单词模式

class Solution {
public:
    bool wordPattern(string ptn, string str) {
        vector<string> words=split(str);
        if(words.size()!=ptn.length())return false;
        map<char,string> map1;//用两个map做双射
        map<string,char> map2;
        int len=ptn.length();
        for(int i=0;i<len;i++){
            /*三种情况:两个map都没有,都有,一个有一个没有
             *都没有:建立双射
             *都有:如果当前的不属于一对映射false
             *有一个:false
            */
            if(!map1.count(ptn[i])&&!map2.count(words[i])){
                map1[ptn[i]]=words[i];
                map2[words[i]]=ptn[i];
            }
            else if(map1.count(ptn[i])&&map2.count(words[i])){
                if(!(map1[ptn[i]]==words[i]&&map2[words[i]]==ptn[i]))return false;
            }
            else return false;
            
        }
        return true;
    }
    
    vector<string> split(string str){
        vector<string> ret;
        int len=str.length();
        int i=0,t=0;
        while(str[i]==' '&&i<len)i++;
        while(i<len){
            t=i;//保留起始位置
            while(str[i]!=' '&&i<len)i++;
            ret.push_back(str.substr(t,i-t));
            while(str[i]==' '&&i<len)i++;

        }
        return ret;
    }   
};

 

posted @ 2019-02-27 22:34  开局一把刀  阅读(3)  评论(0)    收藏  举报