Leetcode_290_Word Pattern

Posted lihello

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode_290_Word Pattern相关的知识,希望对你有一定的参考价值。

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.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

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

题意:一直strpattern,判断strpattern是否匹配。(匹配代表字符创strpattern中的字符一一对应)

解题思路:

  1. 设置字符串到pattern单词的映射(哈希表);使用数字use[128]记录pattern字符是否使用。
  2. 便利str,按照空格拆分单词,同时对应的向前移动指向pattern字符的指针,每拆分出一个单词,判断:
    • 如果该单词从未出现在哈希表中:
      • 如果当前的pattern字符已被使用,返回false
      • 将该单词与当前指向的pattern字符做映射
      • 标记当前指向的pattern字符已被使用
    • 否则:
      • 如果当前单词在哈希表中的映射不是指向当前的pattern字符,则返回false
  3. 若单词个数与pattern字数不匹配,则返回false
class Solution {
public:
    bool wordPattern(std::string pattern, std::string str) {
        std::map<std::string, char> word_map;
        char used[128] = {0};
        std::string word;
        int pos = 0;
        str.push_back(' ');
        for (int i = 0; i < str.length(); i++){
            if (str[i] == ' '){
                if (pos == pattern.length()){
                    return false;
                }
                if (word_map.find(word) == word_map.end()){
                    if (used[pattern[pos]]){
                        return false;
                    }
                    word_map[word] = pattern[pos];
                    used[pattern[pos]] = 1;
                }
                else{
                    if (word_map[word] != pattern[pos]){
                        return false;
                    }
                }
                word = "";
                pos++;
            }
            else{
                word += str[i];
            }
        }
        if (pos != pattern.length()){
            return false;
        }
        return true;
    }
};

以上是关于Leetcode_290_Word Pattern的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode290]Word Pattern

leetcode290. Word Pattern

Leetcode 290. Word Pattern

[leetcode]290.Word Pattern

LeetCode 290. Word Pattern

LeetCode 290 Word Pattern