leetcode 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,一个是map<string,char>一个是map<char,string>
然后就是没有什么难度了,有一个问题就是我在vs2010里mp[pattern[i]]!=v1[i]这句提示不能用“!=”(原来我是没有#include<string>太粗心啦)不过在leetcode的编译器里通过了。
我需要看一下关于字符串的比较。
1 class Solution { 2 public: 3 vector<string> splitString(string s){ 4 vector<string> result; 5 string temp; 6 int length=s.length(); 7 for(int i=0;i<length;i++){ 8 if(s[i]!=' '&&i!=length-1) temp+=s[i]; 9 else { 10 if(i==length-1) temp+=s[i]; 11 result.push_back(temp); 12 temp=""; 13 } 14 } 15 return result; 16 } 17 18 19 bool wordPattern(string pattern, string str) { 20 vector<string> v1; 21 v1=splitString(str); 22 if(pattern.length()!=v1.size()) return false; 23 map<char,string> mp; 24 for(int i=0;i<pattern.length();i++){ 25 if(mp.find(pattern[i])==mp.end()) mp[pattern[i]]=v1[i]; 26 else if(mp[pattern[i]]!=v1[i]) return false; 27 } 28 map<string,char> mp2; 29 for(int i=0;i<pattern.length();i++){ 30 if(mp2.find(v1[i])==mp2.end()) mp2[v1[i]]=pattern[i]; 31 else if(mp2[v1[i]]!=pattern[i]) return false; 32 } 33 return true; 34 } 35 };
这是别人这道题分割字符串的方法,学习了:
1 while (sin >> tmp) dic.push_back(tmp); 2 if (dic.size() != pattern.size()) return false;