leetcode刷题,总结,记录,备忘 290

来源:互联网 发布:制作网页用什么软件 编辑:程序博客网 时间:2024/06/08 07:01

leetcode290 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:

  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.

使用2个map,做两两映射。每个字母和单词分别对应相应的字母和单词,在map中没有该键的时候进行添加,在map中已经有键的时候进行检验,是否相同。

class Solution {public:bool wordPattern(string pattern, string str) {vector<string> vs;while (1){int pos = str.find(" ");if (pos == string::npos){vs.push_back(str);break;}else{vs.push_back(str.substr(0, pos));str = str.substr(pos + 1);}}if (vs.size() != pattern.size()){return false;}map<string, string> ms;map<string, string> ms2;for (int i = 0; i < pattern.size(); ++i){string t;t += pattern[i];if (ms.find(t) == ms.end() && ms2.find(vs[i]) == ms2.end()){ms[t] = vs[i];ms2[vs[i]] = t;}else{if (ms[t] != vs[i] || ms2[vs[i]] != t){return false;}}}return true;}};


0 0
原创粉丝点击