LeetCode刷题笔记--290. Word Pattern

今天调了很久,终于笨方法调出来了。改天有空了优化一下。

290. Word Pattern

Easy

54159FavoriteShare

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.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: 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) {
         map<char,string> mp;
        map<string,char> mp1;
         string temp="";
        vector<string> s;
        string ts="";
        s.clear();
        mp.clear();
        int lenp=pattern.length();
        int lens=str.length();
        int j=0;
        int p=0;
        int lens1=1;
        bool ans=true;
        while(j<lens)
        {
            if(str[j]!=' ')
            {
                ts+=str[j];
                if(j==lens-1)s.push_back(ts);
                    
            }
            else
            {
                s.push_back(ts);
                ts = "";
                p++;
                lens1++;
            }
            j++;
            
        }
        if(lens1!=lenp)return false;
        
        for(int i=0;i<lenp;i++)
        {
            if(mp.find(pattern[i])==mp.end())
            {
                mp[pattern[i]]=s[i];
            }
            else
            {
                if(mp.at(pattern[i])!=s[i])return false;
            }
            if(mp1.find(s[i])==mp1.end())
            {
                mp1[s[i]]=pattern[i];
            }
            else
            {
                if(mp1.at(s[i])!=pattern[i])return false;
            }
            
        }

        return true;
            
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值