作者:小迅
链接:https://leetcode.cn/problems/expressive-words/solutions/1989983/shuang-zhi-zhen-mo-ni-zhu-shi-chao-ji-xi-zo6z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目![](https://img-blog.csdnimg.cn/80ce4c64cef04e3ab10e00137c8d4eea.png)
示例![](https://img-blog.csdnimg.cn/f2bed2266cf847ddbf9e07e421e772ce.png)
思路
对于任意一个字符串 word 能否夸张为 s 需要满足以下条件:
- 相同字符的相对位置一样,相对顺序一样,即 word[i] = s[j],比如不能 sy 和 ys
- 对于任意一个相对位置相同的字符,在 s 中 必须在当前位置存在相同的连续字符,数量必须大于等于 3,当数量小于 3 时,必须与word中的数量相同(相同就不需要扩展),在 word 中当前位置 存在的相同连续字符 数量必须 小于 s 中的数量,
满足上述两个要求即可配对
可以使用双指针按上述规则进行模拟,注意只有到双指针都到达字符串结束符时,才能算都满足上述要求,如果任意一个指针未到达结束符,说明肯定有一个不满足第一个要求。
可以对 word 中相同的字符进行 3 次以上的扩展,其中 相同的字符一起扩展 和 相同的字符单个扩展 相比,单个字符扩展更有优势,更容易被我们控制,www 和 w,www扩展的结果w都可以得到,但是 w 扩展的结果 www 不一定能
代码
int dfs(char * s, char * word)
{
int len1 = strlen(s);
int len2 = strlen(word);
int left1 = 0;
int left2 = 0;//初始化双指针
while (left1 < len1 && left2 < len2) {//枚举每一个位置
if (s[left1] != word[left2]) {//相对位置不一样
return 0;
}
int count1 = 0;
int count2 = 0;//记录相同字符数量
while (left1 + 1 < len1 && s[left1] == s[left1 + 1]) {//统计s中当前连续字符
++left1;
++count1;
}
while (left2 + 1 < len2 && word[left2] == word[left2 + 1]) {//统计word中当前连续字符
++left2;
++count2;
}
if (count1 != count2 && (count1 < 2 || count2 > count1)) {//不满足第二个要求,数量不一样
return 0;
}
++left1;
++left2;
}
if (left1 != len1 || left2 != len2) {//都到结束符才返回1
return 0;
}
return 1;
}
int expressiveWords(char * s, char ** words, int wordsSize){
int sum = 0;
for (int i = 0; i < wordsSize; ++i) {//统计每一个满足要求的子串数量
sum += dfs(s, words[i]);
}
return sum;
}
作者:小迅
链接:https://leetcode.cn/problems/expressive-words/solutions/1989983/shuang-zhi-zhen-mo-ni-zhu-shi-chao-ji-xi-zo6z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
int dfs(const string& s, const string& word)
{
int len1 = s.size();
int len2 = word.size();
int left1 = 0;
int left2 = 0;
while (left1 < len1 && left2 < len2) {
if (s[left1] != word[left2]) {
return 0;
}
int count1 = 0;
int count2 = 0;
while (left1 + 1 < len1 && s[left1] == s[left1 + 1]) {
++left1;
++count1;
}
while (left2 + 1 < len2 && word[left2] == word[left2 + 1]) {
++left2;
++count2;
}
if (count1 != count2 && (count1 < 2 || count2 > count1)) {
return 0;
}
++left1;
++left2;
}
if (left1 != len1 || left2 != len2) {
return 0;
}
return 1;
}
int expressiveWords(string s, vector<string>& words) {
int sum = 0;
for (int i = 0; i < words.size(); ++i) {
sum += dfs(s, words[i]);
}
return sum;
}
};
作者:小迅
链接:https://leetcode.cn/problems/expressive-words/solutions/1989983/shuang-zhi-zhen-mo-ni-zhu-shi-chao-ji-xi-zo6z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。