本节简单记录string中的substr()方法。参数有两个:pos和len;操作就是将string[pos, pos+len]位置字符“切片”得到一个子字符串。
PS:c++中没有split()方法,因此为了得到string的子字符串,需要自己构建split()函数。
https://zh.cppreference.com/w/cpp/string/basic_string/substr
https://blog.csdn.net/sunshihua12829/article/details/50484966
运用:
Leetcode 290. Word 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.
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> words = split(str);
if( pattern.size() != words.size() )
return false;
unordered_map<char, string> resultP;
unordered_map<string, char> resultS;
for( int i = 0; i < pattern.size(); i++ ){
if( resultP.find(pattern[i]) == resultP.end() ){
**//eg: pattern = {"abba"}, str = {"dog dog dog dog"}**
if( resultS.find(words[i]) != resultS.end() )
return false;
resultP[pattern[i]] = words[i];
resultS[words[i]] = pattern[i];
}
else{
string s = resultP[pattern[i]];
if( s != words[i] )
return false;
}
}
return true;
}
private:
vector<string> split(string& s){
vector<string> res;
int start = 0;
for( int i = start+1; i <= s.size(); ){
if( i == s.size() || s[i] == ' ' ){
res.push_back(s.substr(start, i-start));
start = i + 1;
i = start + 1;
}
else
i++;
}
return res;
}
};