leetcode 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.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

思路:

首先把str给分割成单词数组,然后用笨方法,保存双向映射,这就是为什么代码中设置两个map。遍历数组,用map来查找和插入映射。

代码:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        //split into word list
        vector<string> wordlist;
        string::size_type pos;
        str += " ";
        int size = str.size();
        for (int i = 0; i < size; i++)
        {
            pos = str.find(" ", i);  //find the space position
            if (pos < size)
            {
                string word = str.substr(i, pos - i); //extract the word
                if (word != "") //record the word
                {
                    wordlist.push_back(word);
                }
                i = pos;
            }
        }
        int w_size = wordlist.size();
        int p_size = pattern.size();
        if (w_size != p_size) return false;
        map<char, string> c2s_mapped;  //map char to string
        map<string, char> s2c_mapped;  //map string to char
        for (int i = 0; i < p_size; i++)
        {
            char c_now = pattern[i];
            string s_now = wordlist[i];
            map<char, string>::iterator it_c2s = c2s_mapped.find(c_now);
            if (it_c2s != c2s_mapped.end())  //found
            {
                if (it_c2s->second != s_now) return false;
            }
            else  //not found
            {
                map<string, char>::iterator it_s2c = s2c_mapped.find(s_now);
                if (it_s2c != s2c_mapped.end()) return false;

                c2s_mapped.insert(pair<char, string>(c_now, s_now));
                s2c_mapped.insert(pair<string, char>(s_now, c_now));
            }
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值