LeetCode第 290 题:单词规律(C++)

290. 单词规律 - 力扣(LeetCode)

和这题类似:LeetCode第 205 题:同构字符串(C++)_zj-CSDN博客

先来个哈希表的把:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int n = pattern.size();
        unordered_map<int, string> m;
        vector<string> vec;//保存单词
        string s;
        for(const auto &c : str){
            if(isspace(c)){
                vec.push_back(s);
                s.clear();
                continue;
            } 
            s += c;
        }
        vec.push_back(s);
        if(n != vec.size()) return false;

        for(int i = 0; i < n; ++i){
            if(m.count(pattern[i])){
                if(m[pattern[i]] != vec[i]) return false;
            }else{
                for(auto v : m){//此处可以优化,多一个哈希表set就可以免去查找
                    if(v.second == vec[i])  return false;
                }
                m[pattern[i]] = vec[i];
            }
        }
        return true;
    }
};

进行优化,使用哈希函数编码:

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        vector<int> m(26, -1);
        unordered_set<int> set;
        int i = 0;
        for(const auto &c : pattern){
            int hash = 0;
            for(; i < str.size() && isalpha(str[i]); ++i){//计算哈希值
                hash += (str[i]-'a')*(str[i]-'a') + 1;//这个哈希函数就是随便设计的
            }
            ++i;//跳过当前的空格
            if(m[c-'a'] != -1){
                if(m[c-'a'] != hash) return false;
            }else{
                if(set.count(hash)) return false;//已经有元素指向它了
                set.insert(hash);
                m[c-'a'] = hash;
            }
        }
        if(i != str.size()+1) return false;//因为for循环下面有有一个++i
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值