解题思路:
看完题目就很容易想到双指针,将s与每个word进行比较,用两个指针分别指向两个单词,比较对应位置是否相等,连续相等字母的expand是否超过3,比较过程封装成函数返回true或者false,代码如下:
class Solution {
public:
int expressiveWords(string s, vector<string>& words) {
int res = 0;
for(auto& word : words) {
if(expand(s, word)) {
res ++;
}
}
return res;
}
bool expand(string& s, string& word) {
int n1 = s.size(), n2 = word.size();
int index1 = 0, index2 = 0;
while(index1 < n1 && index2 < n2) {
// 对应位置不相等
if(s[index1] != word[index2]) {
return false;
}
char c = s[index1];
int count1 = 0;
while(index1 < n1 && s[index1] == c) {
count1 ++;
index1 ++;
}
int count2 = 0;
while(index2 < n2 && word[index2] == c) {
count2 ++;
index2 ++;
}
// 如果扩张还不如没扩张
if(count1 < count2) {
return false;
}
// 扩张了但是不够数
if(count1 != count2 && count1 < 3) {
return false;
}
}
return index1 == n1 && index2 == n2;
}
};