leetcode 205. Isomorphic Strings、290. Word Pattern、890. Find and Replace Pattern

目录

一、205. 同构字符串

二、290. 单词规律

三、890. 查找和替换模式


这三道题目其实一模一样。

、205. 同构字符串

代码:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char,char> s2t;
        unordered_map<char,char> t2s;
        int len = s.size();
        for(int i=0;i <len;i++){
            char sc = s[i];
            char tc = t[i];
            if((s2t.contains(sc)&&s2t[sc]!=tc) || (t2s.contains(tc)&&t2s[tc]!=sc))
                return false;
            s2t[sc] = tc;
            t2s[tc] = sc;
        }
        return true;
    }
};

二、290. 单词规律

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        vector<string> strvec;
        int slen = s.size();
        int start = 0;
        int len = 0;
        for(int i = 0;i <slen;i++){
            if(s[i] != ' '){
                len++;
            }
            else{
                strvec.push_back(s.substr(start,len));
                start=i+1;
                len = 0;
            }
        }
        strvec.push_back(s.substr(start,len));

        int pattern_len = pattern.size();
        if(pattern_len != strvec.size())
            return false;
        unordered_map<char,string> pattern2str;
        unordered_map<string,char> str2pattern;
        for(int i = 0; i<pattern_len;i++){
            if((pattern2str.contains(pattern[i])&&pattern2str[pattern[i]]!=strvec[i]) ||
               (str2pattern.contains(strvec[i])&&str2pattern[strvec[i]]!=pattern[i]) )
                return false;
            pattern2str[pattern[i]] = strvec[i];
            str2pattern[strvec[i]] = pattern[i];
        }
        return true;
    }
};

三、890. 查找和替换模式

代码:

class Solution {
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string> res;
        for(const string &word:words)
        {
            if(match(word,pattern))
                res.push_back(word);
        }
        return res;
    }
    bool match(const string word,const string &pattern){
        unordered_map<char,char> word2pattern;
        unordered_map<char,char> pattern2word;
        int len = word.size();
        for(int i = 0;i < len;i++){
            if((word2pattern.contains(word[i])&&word2pattern[word[i]]!=pattern[i]) ||
               (pattern2word.contains(pattern[i])&&pattern2word[pattern[i]]!=word[i]))
               return false;
            word2pattern[word[i]] = pattern[i];
            pattern2word[pattern[i]] = word[i];
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值