zoukankan      html  css  js  c++  java
  • leetcode 290. Word Pattern

    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:
    pattern = "abba", str = "dog cat cat dog" should return true.
    pattern = "abba", str = "dog cat cat fish" should return false.
    pattern = "aaaa", str = "dog cat cat dog" should return false.
    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.

    Credits:
    Special thanks to @minglotus6 for adding this problem and creating all test cases

    把字符数组和字符串数组,映射到‘a’~'z'然后 判断两个映射后的字符串是否相等就行

    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            map<string, char> mp;
            string t = "";
            int k = 0;
            string ans = "";
            for (int i = 0; i < str.size(); ++i) {
                if (str[i] == ' ') {
                    if (!mp[t]) {
                        mp[t] = char(k + 'a');
                        ++k;
                    }
                    ans += mp[t];
                    t = "";
                }
                else t += str[i];
            }
            if (t.size()) {
                if (mp[t]) ans += mp[t];
                else mp[t] = char(k + 'a'), ans += mp[t];
            }
            map<char, char> mp2;
            string w = "";
            k = 0;
            for (int i = 0; i < pattern.size(); ++i) {
                if (!mp2[pattern[i]]) {
                    mp2[pattern[i]] = char(k + 'a');
                    ++k;
                }
                w += mp2[pattern[i]];
            }
            return ans == w;
        }
    };
    
  • 相关阅读:
    前端知识体系(一)浏览器机制以及进程线程的关系
    页面之间的通信
    DOM
    浏览器内核及浏览器对象
    js正则表达式
    setTimeout和setInterval
    原生js操作cookie
    apply、call、bind方法调用
    一个简单的hexo搭建博客网站的故事
    debug for bin runtime error
  • 原文地址:https://www.cnblogs.com/pk28/p/7467656.html
Copyright © 2011-2022 走看看