290. Word Pattern

来源:互联网 发布:2017最火的中文编程 编辑:程序博客网 时间:2024/06/06 15:04

290. Word Pattern
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:

pattern = "abba", str = "dog cat cat dog" should return true.pattern = "abba", str = "dog cat cat fish" should return false.pattern = "aaaa", str = "dog cat cat dog" should return false.pattern = "abba", str = "dog dog dog dog" should return false.
  1. 感觉自己的方法比较笨,不过相对自己以前的编码习惯,在按照空格分割string时,引用istringstream的确是一种比较快捷的方法。

解决这个问题的主要思想:

  1. pattern:abba,我们编码为0110;对于pattern中的每个字符,我们将其映射到其第一次出现的位置,这个可以直接利用string的find_first_of得到。
  2. str = “dog cat cat fish”,我们编码为0113;对于vector来说,如何实现将每个单词映射到其第一次出现的位置,我引用了map。
class Solution {public:    bool wordPattern(string pattern, string str) {        int* patternCode=new int[pattern.size()];//对pattern进行编码        for(unsigned int i=0;i<pattern.size();i++)            patternCode[i]=pattern.find_first_of(pattern[i]);        vector<string> vec;        map<string,int> strMap;        istringstream ss(str);        string word;        while(ss>>word)            vec.push_back(word);//分割str为单词,存储在vector中        int* strCode=new int[vec.size()];        for(unsigned int i=0;i<vec.size();i++)//为str进行编码        {            if(!strMap.count(vec[i]))            {                strMap[vec[i]]=i;                strCode[i]=i;            }            else                strCode[i]=strMap[vec[i]];        }        if(pattern.size()!=vec.size())//两者编码长度不同,返回错误            return false;        for(unsigned int i=0;i<vec.size();i++)            if(patternCode[i]!=strCode[i])                return false;        return true;    }};
0 0
原创粉丝点击