[Leetcode ]290. Word Pattern

  1. Word Pattern
    Easy

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.

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

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

示例1:

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

输入:pattern = “abba”, str = “dog cat cat fish”
输出: false
示例 3:

输入: pattern = “aaaa”, str = “dog cat cat dog”
输出: false
示例 4:

输入: pattern = “abba”, str = “dog dog dog dog”
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。

解题思路:此题和205同构字符串是同一个套路。
理由hash表,把字符和字符串相互映射,然后判断。
代码:
class Solution {
public:
bool wordPattern(string pa, string str) {

    if(pa.size() ==0 || str.length() == 0 ) return false;       
  
unordered_map < char ,string > ch;
unordered_map < string ,char> s;       
vector <string> re(pa.size());        
int j=0;               
    
for( int  i = 0; i < pa.size(); i++)
    {
        if(j>=str.length())return false; // pattern字符数比str中的单词数多。
        while( j < str.length() ) //把某个单词读取出来
        {
            if (str[j] != ' ')
            {
                re[i]+=str[j];
                 j++;
            }
            else
            {
                j++;
                break;
            }
        }
         if(ch.count(pa[i]) && s.count(re[i]) )
         {
             if(ch[pa[i]] != re[i])
                 return false;                     
         }
          else if (ch.count(pa[i]) || s.count(re[i]) )
                    return false;
                else {                  
                        ch[pa[i]] = re[i];
                       s[re[i]] = pa[i];
                    }          
       }
    if (j < str.length()) return false; //str中的单词数比pattern中的字符多。
    
    return true;
}

};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值