Leetcode 290. Word Pattern

Posted Deribs4

tags:

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

290. Word Pattern

Total Accepted: 42115 Total Submissions: 140014 Difficulty: Easy

 

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.

 

思路:映射。详细可以参考Leetcode 205. Isomorphic Strings的第一个方法

代码:

注意istringstream的用法,头文件<sstream>。这个可以专门用来分解含空格的字符串

 1 class Solution {
 2 public:
 3     bool wordPattern(string pattern, string str) {
 4         map<char,int> p2i;
 5         map<string,int> s2i;
 6         string temp;
 7         int i=0,n=pattern.size();
 8         istringstream in(str);
 9         while(in>>temp){
10             if(i<n){
11                 //map中没有对应的键-值对,则返回0
12                 if(p2i[pattern[i]]!=s2i[temp]){
13                     return false;
14                 }
15                 p2i[pattern[i]]=s2i[temp]=i+1;
16             }
17             i++;
18         }
19         return i==n;
20     }
21 };

 

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

LeetCode_290. Word Pattern

[leetcode]290.Word Pattern

leetcode?python 290. Word Pattern

leetcode290. Word Pattern

LeetCode 290. Word Pattern

Leetcode_290_Word Pattern