leetcode:290 Word Pattern-每日編程第三十九題

Word Pattern

Total Accepted: 19405 Total Submissions: 71219 Difficulty: 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.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int leftIndex=0;
        int rightIndex=0;
        int len=pattern.length();
        int len1=str.length();
        
        map<char,string> ma;
        map<char,string>::iterator it;
        
        map<string,char> ma1;
        map<string,char>::iterator it1;
        
        for(int i=0;i<len;i++){
            while(rightIndex<len1&&str[rightIndex]!=' '){
                rightIndex++;
            }
            if(rightIndex==leftIndex){
                return false;
            }
            string temp=str.substr(leftIndex,rightIndex-leftIndex);
            if((it=ma.find(pattern[i]))!=ma.end()){
                if(it->second!=temp){
                    return false;
                }
            }else{
                ma[pattern[i]]=temp;
            }
            leftIndex=++rightIndex;
            
            if((it1=ma1.find(temp))!=ma1.end()){
                if(it1->second!=pattern[i]){
                    return false;
                }
            }else{
                ma1[temp]=pattern[i];
            }
        }
        if(rightIndex<len1){
            return false;
        }
        return true;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章