828. 字模式

描述

给定一个模式和一个字符串str,查找str是否遵循相同的模式。
这里遵循的意思是一个完整的匹配,在一个字母的模式和一个非空的单词str之间有一个双向连接的模式对应。

您可以假设模式只包含小写字母,而str包含由单个空间分隔的小写字母。

您在真实的面试中是否遇到过这个题?   是

样例

给定模式= "abba", str = "dog cat cat dog",返回true。给定模式= "abba", str = "dog cat cat fish",返回false
给定模式= "aaaa", str = "dog cat cat dog",返回false。给定模式= "abba", str = "dog dog dog dog",返回false

感觉自己的方法虽然思路简单,但是空间复杂度太高了。

class Solution {
public:
    /**
     * @param pattern: a string, denote pattern string
     * @param str: a string, denote matching string
     * @return: an boolean, denote whether the pattern string and the matching string match or not
     */
    bool wordPattern(string &pattern, string &str) {
        // write your code here
        vector<string> result;
        string tmp;
        for(int i=0;i<str.length();i++){
            if(str[i]==' '&&tmp.length()>0){
                result.push_back(tmp);
                tmp="";
            }else tmp+=str[i];
        }
        if(tmp.length()>0) result.push_back(tmp);
        unordered_map<char,string> m_map1;
        unordered_map<string,char> m_map2;
        for(int i=0;i<pattern.length();i++){
            if(m_map1.count(pattern[i])==0) {
                m_map1[pattern[i]]=result[i];
                m_map2[result[i]]=pattern[i];
            }
            else if(m_map1[pattern[i]]!=result[i]||m_map2[result[i]]!=pattern[i]) return false;
        }
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值