前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 290. Word Pattern

Leetcode 290. Word Pattern

作者头像
triplebee
发布2018-03-27 16:53:55
6320
发布2018-03-27 16:53:55
举报

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

判断字符串是否是模式串的形式。

对字符串进行分词,用map保存和模式串字符的对应关系

代码语言:javascript
复制
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        str += " ";
        int j = 0;
        unordered_map<string, string> mp;
        for(int i = 0; i < str.size(); i++)
        {
            int pos = str.find(" ", i);
            string tmp = str.substr(i, pos - i);
            i = pos;
            if(j == pattern.size()) return false;
            string key(pattern[j] + "\0");
            if(mp.find(key) == mp.end())
            {
                if(mp.find(tmp) == mp.end()) 
                {
                    mp[tmp] = key;
                    mp[key] = tmp;
                }
                else return false;
            }
            else if(mp[key] != tmp) return false;
            j++;
        }
        if(j != pattern.size()) return false;
        return true;
    }
};         
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档