LeetCode 面试经典150题 [40/150 单词规律]


avatar
GuoYulong 2024-06-26 60

题目描述

给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
示例 1:

输入: pattern = "abba", s = "dog cat cat dog"
输出: true

示例 2:

输入:pattern = "abba", s = "dog cat cat fish"
输出: false

个人C++解答

和上道题一样,反正都是O(n),就没必要创两个哈希表了,虽然好看,但是还是比较浪费内存的

GYL
class Solution {
public:
    bool wordPattern(string pattern, string s) {
        string Map[26];
        fill(Map, Map + 26, string(" "));
        int index_l = 0, index_r = 0;
        for (int i = 0; i < pattern.size(); i++) {
            if(index_r == s.size()) return false;
            s = s.substr(index_l, s.size());
            index_r = s.find(' ') != string::npos ? s.find(' ') : s.size();
            string str_com = s.substr(0, index_r);
            for (int j = 0; j < 26; j++) {
                if (Map[j].compare(str_com) == 0 && j != pattern[i] - 'a') {
                    return false;
                }
            }
            if (Map[pattern[i] - 'a'] == " ") {
                Map[pattern[i] - 'a'] = str_com;
            } else if (Map[pattern[i] - 'a'].compare(str_com) == 0) {

            } else {
                return false;
            }
            index_l = index_r + 1;
        }
        if(index_r!=s.size()) return false;
        return true;
    }
};

相关阅读

注意!!!

新增会员中心页面,方便管理个人账户,充值功能暂不开启,请勿为本网站进行任何充值活动!!!

通知!!!

① 过年好!!!拖更几个月了已经,年后继续更新!!