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.
1. Thoughts
- The first element in the string str a space as a boundary extracted sequentially stored in the vector;
- Through the double loop, which two at the pattern team, and comparison str elements in the same position are the same;
- If the same pattern, but differ in str, then return false;
- If the pattern is different, but the same str, then return false;
- If traverse all have no return value, then return true.
2. To achieve
the Runtime: 0ms (100%)
Memory: 9MB (6.09%)
class Solution {
public:
bool wordPattern(string pattern, string str) {
int len = pattern.size();
vector<string> st;
int ln = str.size();
string s = str;
while(1){
int pos = s.find(' ');
if(pos>0){
st.push_back(s.substr(0, pos));
s = s.substr(pos+1);
}
else{
st.push_back(s);
break;
}
}
if(st.size() != len)
return false;
for(int i=0; i<len; i++){
for(int j=i+1; j<len; j++){
if(pattern[i] == pattern[j]){
if(st[i] != st[j]){
return false;
}
}
else{
if(st[i] == st[j]){
return false;
}
}
}
}
return true;
}
};