LeetCode Word Pattern

来源:互联网 发布:淘宝商品找不到了 编辑:程序博客网 时间:2024/06/16 01:00

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.

解题思路:首先对str进行单词split存放到vector中,然后利用两个map结构,分别检查char与string是否一一对应

class Solution {public:    bool wordPattern(string pattern, string str) {        //解题思路:首先对str采用split分出所有单词,然后将pattern中的每个字母与单词绑定,如果存在不匹配的false        int index = 0;        int start = 0;        int n = str.length();        vector<string> words;        while(str[index] != '\0')        {            if(str[index] != ' ')                ++index;            else            {                words.push_back(str.substr(start,index-start));                start = index+1;                ++index;            }        }        words.push_back(str.substr(start,n-start));                if(words.size() != pattern.size())  return false;        map<char,string>  sta;        map<string,char>  sta1;        for(int i = 0;i<pattern.size();i++)        {             //cout<<words[i]<<endl;             if(sta.count(pattern[i]) == 0)                 sta[pattern[i]] = words[i];             else             {                 string s = sta[pattern[i]];                 if(s != words[i])                    return false;             }                          if(sta1.count(words[i]) == 0)                 sta1[words[i]] = pattern[i];             else             {                 char c = sta1[words[i]];                 if(c != pattern[i])                    return false;             }        }        return true;    }};


0 0
原创粉丝点击