0
点赞
收藏
分享

微信扫一扫

单词规律(字符串,map,leetcode290)-------------------c++实现

穆熙沐 2022-05-01 阅读 79
c++leetcode

单词规律(字符串,map,leetcode290)-------------------c++实现

题目表述

给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。

这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。

样例

输入: pattern = “abba”, str = “dog cat cat dog”
输出: true

条件

1 <= pattern.length <= 300
pattern 只包含小写英文字母
1 <= s.length <= 3000
s 只包含小写英文字母和 ’ ’
s 不包含 任何前导或尾随对空格
s 中每个单词都被 单个空格 分隔

思路

两个map结构为了保证一一对应!

注意点

在这里插入图片描述在这里插入图片描述
unordered判断方法来说
此题x.count(z)方法比x.find(z)!=sc,end()快

ac代码

c++:

class Solution {
public:
    bool wordPattern(string pattern, string s) {
          unordered_map<char,string> cs;
          unordered_map<string,char> sc;
          int ssum=s.size();
          int i=0;
          for(auto x:pattern)
          {
              if(i>ssum)
              return false;
              int j=i;
              while(j<ssum&&s[j]!=' ')
              j++;
              string z = s.substr(i,j-i);
              if(sc.find(z)!=sc.end()&&sc[z]!=x)
                       return false;
              if(cs.find(x)!=cs.end()&&cs[x]!=z)
              return false;
              cs[x]=z;
              sc[z]=x;
              i=j+1;
          }
          return i==ssum+1;
    }
};
举报

相关推荐

0 条评论