290. 单词规律

290. 单词规律


题目链接:290. 单词规律

代码如下:

cpp 复制代码
class Solution {
public:
    bool wordPattern(string pattern, string s) {
        unordered_map<char,string> um;
        vector<string> strs;
        string str="";

        //把字符串中单词都保存到集合中
        for(int i=0;i<s.size();i++)
        {
            if(s[i]==' ')
            {
                strs.push_back(str);
                str="";
            }
            else
            {
                str+=s[i];
            } 
        }
        strs.push_back(str);

        //二者长度不同直接返回即可
        if(pattern.size()!=strs.size())
            return false;

        逐个对比
        for(int i=0;i<pattern.size();i++)
        {
            //未找到的情况
            if(um.find(pattern[i])==um.end())
            {
                看是否已于别的字母建立联系,是的话就直接返回,不满住一对一了
                for(auto it=um.begin();it!=um.end();it++)
                {
                    if(it->second==strs[i])
                        return false;
                }

                //插入
                um[pattern[i]]=strs[i];
            }
            //不满足一对一直接返回
            else if(strs[i]!=um[pattern[i]])
                return false;
        }

        return true;

    }
};
相关推荐
明月醉窗台12 分钟前
Qt 入门 1 之第一个程序 Hello World
开发语言·c++·qt
hy____12335 分钟前
类与对象(中)(详解)
开发语言·c++
wen__xvn40 分钟前
c++STL入门
开发语言·c++·算法
the_nov1 小时前
20.IP协议
linux·服务器·网络·c++·tcp/ip
只有月亮知道1 小时前
C++list常用接口和模拟实现
开发语言·c++
勘察加熊人1 小时前
c#和c++脚本解释器科学运算
开发语言·c++·c#
zyx没烦恼2 小时前
Linux 下 日志系统搭建全攻略
linux·服务器·开发语言·c++
MCYH02063 小时前
C++抽卡模拟器
java·c++·算法·概率·原神
pystraf3 小时前
P10587 「ALFR Round 2」C 小 Y 的数 Solution
数据结构·c++·算法·线段树·洛谷
郭涤生4 小时前
The whole book test_《C++20Get the details》_notes
开发语言·c++·笔记·c++20