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 };

 

posted @ 2016-07-01 12:03  Deribs4  阅读(235)  评论(0编辑  收藏  举报