码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode_290_Word Pattern

时间:2019-10-27 20:32:33      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:The   use   个数   out   指针   solution   not   word   put   

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

标签:The   use   个数   out   指针   solution   not   word   put   

原文地址:https://www.cnblogs.com/lihello/p/11748537.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!