首页 > 其他 > 详细

leetcode 290 Word Pattern(map的应用)

时间:2016-02-27 19:19:26      阅读:151      评论:0      收藏:0      [点我收藏+]

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.

题解:很简单,用两个map记录就可以。

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int len_p=pattern.length();
        int len_s=str.length();
        vector<string>v(1);
        int id=0;
        for(int i=0;i<len_s;i++){
            if(str[i]== ){
                id++;
                v.push_back(string());
            }
            else{
                v[id]+=str[i];
            }
        }
        
        if(len_p!=(id+1)){
            return false;
        }
        
        else{
            map<char,string>mp;
            map<string,char>mp2;
            
            for(int i=0;i<len_p;i++){
                if(mp.count(pattern[i])==0){
                    if(mp2.count(v[i])==0){
                        mp[pattern[i]]=v[i];
                        mp2[v[i]]=pattern[i];
                    }
                    else{
                        return false;
                    }
                }
                else{
                    if(mp[pattern[i]]!=v[i]){
                        return false;
                    }
                }
            }
            return true;
        }
    }
};

 

leetcode 290 Word Pattern(map的应用)

原文:http://www.cnblogs.com/zywscq/p/5223362.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!