【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.

思路

最开始的思路是建立两个map,一个从char映射到string,一个从string映射到char。比较好的思路是保存一个相同的值,在这个题中就是出现的位置+1。+1的作用是避免0的干扰,因为map默认值就是0。

代码

class Solution {
public:
    bool wordPattern(string pattern, string str) {
         unordered_map<char,int> p2i;
         unordered_map<string,int> s2i;
         istringstream ss(str);
         int i=0,n=pattern.size();
         for (string word;ss>>word;++i){
             if (i==n || p2i[pattern[i]]!=s2i[word]) return false;
             p2i[pattern[i]]=s2i[word]=i+1;
         }
         return i==n;

    }
};

字符串处理小技巧

此题中string中有空格,而c++中没有很方便的split函数,所以使用istringstream来处理string输入流。注意在平常使用时要包含头文件include <sstream>

转载请声明原文地址

你可能感兴趣的:(LeetCode,C++,String)