leetcode 290 单词模式

class Solution {
public:
    bool wordPattern(string ptn, string str) {
        vector<string> words=split(str);
        if(words.size()!=ptn.length())return false;
        map<char,string> map1;//用两个map做双射
        map<string,char> map2;
        int len=ptn.length();
        for(int i=0;i<len;i++){
            /*三种情况:两个map都没有,都有,一个有一个没有
             *都没有:建立双射
             *都有:如果当前的不属于一对映射false
             *有一个:false
            */
            if(!map1.count(ptn[i])&&!map2.count(words[i])){
                map1[ptn[i]]=words[i];
                map2[words[i]]=ptn[i];
            }
            else if(map1.count(ptn[i])&&map2.count(words[i])){
                if(!(map1[ptn[i]]==words[i]&&map2[words[i]]==ptn[i]))return false;
            }
            else return false;
            
        }
        return true;
    }
    
    vector<string> split(string str){
        vector<string> ret;
        int len=str.length();
        int i=0,t=0;
        while(str[i]==' '&&i<len)i++;
        while(i<len){
            t=i;//保留起始位置
            while(str[i]!=' '&&i<len)i++;
            ret.push_back(str.substr(t,i-t));
            while(str[i]==' '&&i<len)i++;

        }
        return ret;
    }   
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值