码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-290-Word Pattern]

时间:2017-10-16 23:28:09      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:double   ++   class   logs   存储   cti   note   between   empty   

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分别存储pattern对应的单词,以及单词对应的pattern。

bool wordPattern(string pattern, string str)
{
    stringstream ss(str);
    map<string, char>s2ch;
    map<char, string>ch2s;
    vector<string>s;
    string temp;
    while (ss >> temp) s.push_back(temp);     
    if (s.size() != pattern.length())return false;

    for (int i = 0; i < s.size();i++)
    {
        if (s2ch[s[i]] == 0 && ch2s[pattern[i]] == "")
        {
            s2ch[s[i]] = pattern[i];
            ch2s[pattern[i]] = s[i];
            continue;
        }
        if (s2ch[s[i]] != pattern[i]) return false;
    }
    return true;
}

参考:

https://discuss.leetcode.com/topic/26313/0ms-c-solution-using-istringstream-and-double-maps

 

[leetcode-290-Word Pattern]

标签:double   ++   class   logs   存储   cti   note   between   empty   

原文地址:http://www.cnblogs.com/hellowooorld/p/7679268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!