290.单词规律

Given a pattern and a string s, find if s 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 s.

Example 1:

Input: pattern = “abba”, s = “dog cat cat dog”
Output: true
Example 2:

Input: pattern = “abba”, s = “dog cat cat fish”
Output: false
Example 3:

Input: pattern = “aaaa”, s = “dog cat cat dog”
Output: false
Example 4:

Input: pattern = “abba”, s = “dog dog dog dog”
Output: false

Constraints:

1 <= pattern.length <= 300
pattern contains only lower-case English letters.
1 <= s.length <= 3000
s contains only lower-case English letters and spaces ’ '.
s does not contain any leading or trailing spaces.
All the words in s are separated by a single space.
请添加图片描述

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        vector<int> Pattern(26, 0);                                     //记录出现过的小写字母
        vector<string> S(26, "");                                       //与小写字母对应记录对应单词
        int size = pattern.size(), sSize = s.size();                    
        int p = 0;                                                      //坐标

        for (int i = 0; i < size; i++)
        {
            if (Pattern[pattern[i] - 'a'] == 0)                         //该小写字母未出现过
            {
                Pattern[pattern[i] - 'a'] = 1;
                while (p < sSize && s[p] != ' ')
                {
                    S[pattern[i] - 'a'].push_back(s[p++]);              //记录该小写字母对应的单词
                }   
                
                for(int j=0;j<26;j++)                                   //查看该小写字母对应的单词是否与其他字母重复
                {
                    if(S[pattern[i]-'a']==S[j]&&(pattern[i]-'a')!=j)
                    {
                        return false;
                    }
                }
                p++;
            }

            else                                                        //该小写字母已出现过
            {
                int pp = 0;
                while (p < sSize && s[p] != ' ')                        //判断单词是否对应
                {
                    if (S[pattern[i] - 'a'][pp++] != s[p++])
                        return false;
                }
                p++;
            }
        }
        if(p!=sSize+1)return false;                                        //判断是否出现单词多于或少于pattern情况
        return true;
    }
};

还没学过哈希。明天看看题解

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值