290. 单词规律-LeetCode(C++)

290. 单词规律

2024.9.12

题目

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

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

提示:

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

示例1:

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

示例 2:

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

示例 3:

输入: pattern = "aaaa", s = "dog cat cat dog"
输出: false
反思

1.我们得到了一个新的角度来看待hashmap,即:键与值之间的单射关系。如果我们想维护双射关系,那么必须用到两个hashmap

2.还是老问题啊,多考虑下边界,有可能pattern和s数量不对等。

3.多摸摸c++基础语法。

题解

【双向连接的对应规律】,这说明pattern和每一个子串之间是双射关系,即pattern[i] 可以确定一个 string,一个string也可以确定一个pattern[i]。

class Solution {
public:
    std::vector<std::string> splitStringBySpace(const std::string& str) {
        std::vector<std::string> result;
        std::istringstream iss(str);
        std::string word;

        while (iss >> word) {
            result.push_back(word);
        }

        return result;
    }

    bool wordPattern(string pattern, string s) {
        std::vector<std::string> words = splitStringBySpace(s);
        if (pattern.size() != words.size()) {
            return false;
        }
        std::unordered_map<char, string> char2string;
        std::unordered_map<string, char> string2char;
        for (int i = 0; i < pattern.size(); i++) {
            char c = pattern[i];
            std::string word = words[i];
            if (char2string.find(c) != char2string.end()) {
                if (char2string[c] != word) {
                    return false;
                }
            } else {
                char2string[c] = word;
            }
            if (string2char.find(word) != string2char.end()) {
                if (string2char[word] != c) {
                    return false;
                }
            } else {
                string2char[word] = c;
            }
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值