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:

  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.


给定一个模式(pattern)和字符串(str),判断字符串是否遵循这个模式。

这意味着str与pattern是双向映射的,即一个str只对应一个pattern,一个pattern也只对应一个str。

例如:

  1. pattern = "abba", str = "dog cat cat dog" 返回真。
  2. pattern = "abba", str = "dog cat cat fish" 返回假。(第一个a < - > dog,然而最后一个a < - > fish)
  3. pattern = "aaaa", str = "dog cat cat dog" 返回假。(第一个a < - >dog,然而第二个a < - > cat)
  4. pattern = "abba", str = "dog dog dog dog" 返回假。(第一个a < - > dog,然而第一个b也b < - > dog)


由于我只会map,因此在建立双向映射的时候采取的办法是在每一个pattern后面加一个" "(即空格)来区分(以防止出现str为单个字母导致重复映射的情况)。大致思路是将str按空格分割放入vector<string>中,然后按顺序判断pattern与vector的每一对元素,若pattern或str出现过,那么判断对应映射是否正确;否则建立一对新的映射关系。


字符串分割算是自己勉勉强强写出来了,然而对于字符串的使用还是不够熟练。可以看到在判断循环中我先将pattern[i]来push_back给test,然后又append了一个空格进去。。。本来想直接用重载运算符+来直接写进去,但是好像并不能直接写的样子。

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        map<string,string> mapl;
        vector<string> vec;
        str.append(" ");
        for(int start=0,count=0;start<str.length();count++)
        {
            if(str[start+count]==' ')
            {
                vec.push_back(str.substr(start,count));
                start+=count+1;
                count=0;
            }
        }
        if(pattern.length()!=vec.size()) return false;
        for(int i=0;i<pattern.length();i++)
        {
            string test;
            test.push_back(pattern[i]);
            test.append(" ");
            if(mapl.count(test)||mapl.count(vec[i]))
            {
                
                if(mapl[test]!=vec[i]||mapl[vec[i]]!=test) return false;
            }
            else
            {
                mapl[test]=vec[i];
                mapl[vec[i]]=test;
            }
        }
        return true;
    }
};

这里推荐一篇博客,对C++的字符串函数有非常非常详尽的解释,强烈推荐。另外,如果对于C++ STL有像这样介绍详细的博客(关键是要有清晰的成员函数列表及其对应函数参数,不需要使用实例),也请推荐给我,谢谢。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值