首页 > 其他 > 详细

Word Pattern

时间:2015-10-17 12:02:45      阅读:163      评论: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.

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int i = 0;
        istringstream stream(str);
        unordered_map<char, string> chtostr;
        unordered_map<string, char> strtoch;
        string word;
        vector<string> str2;
        while (stream >> word)
            str2.push_back(word);
        if (pattern.size() != str2.size())
            return false;
        for (; i < pattern.size(); i++)
        {
            auto findPtr = chtostr.find(pattern[i]);
            if (findPtr != chtostr.cend())
            {
                if (findPtr->second != str2[i])
                    return false;
            }
            else
                chtostr.insert({ pattern[i], str2[i] });
        }
        i = 0;
        for (; i < str2.size(); i++)
        {
            auto findPtr = strtoch.find(str2[i]);
            if (findPtr != strtoch.cend())
            {
                if (findPtr->second != pattern[i])
                    return false;
            }
            else
                strtoch.insert({str2[i], pattern[i]});
        }
        return true;
    }
};
  • 和之前做的是一样的,建立两个对应表,然后对照下是否一样
  • map的find返回的是一个pair的迭代器,第一个是key,第二个是值

Word Pattern

原文:http://www.cnblogs.com/dylqt/p/4887181.html

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