Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii". Here, we have groups, of adjacent letters that are all the same character, and adjacent characters to the group are different. A group is extended if that group is length 3 or more, so "e" and "o" would be extended in the first example, and "i" would be extended in the second example. As another example, the groups of "abbcccaaaa" would be "a", "bb", "ccc", and "aaaa"; and "ccc" and "aaaa" are the extended groups of that string.
For some given string S, a query word is stretchy if it can be made to be equal to S by extending some groups. Formally, we are allowed to repeatedly choose a group (as defined above) of characters c
, and add some number of the same character c
to it so that the length of the group is 3 or more. Note that we cannot extend a group of size one like "h" to a group of size two like "hh" - all extensions must leave the group extended - ie., at least 3 characters long.
Given a list of query words, return the number of words that are stretchy.
Example: Input: S = "heeellooo" words = ["hello", "hi", "helo"] Output: 1 Explanation: We can extend "e" and "o" in the word "hello" to get "heeellooo". We can't extend "helo" to get "heeellooo" because the group "ll" is not extended.
Notes:
0 <= len(S) <= 100
.0 <= len(words) <= 100
.0 <= len(words[i]) <= 100
.
S
and all words inwords
consist only of lowercase letters
给出一个长字符串S, 以及一个words list。 Words 里面每个word,可以通过扩展当前的char,来尝试构造S。extend的规则是,S中的char,必须连续出现>=3 才可以extend。问,words里面会有几个word 能够extend到S中。
class Solution {
public int expressiveWords(String S, String[] words) {
int res = 0;
for(int n = 0; n < words.length; n++ ){
//遍历每个 单词, 只需要考虑word 长度小于S的,否则肯定不能作为result。
if(words[n].length() <= S.length()){
//两个指针, 分别从头开始遍历word 和S
int i, j;
for (i = 0, j = 0; j < S.length(); j++) {
//如果当前i没有到达word 末尾。且 当前word的char == S的char, 则将i指针向前移动。
if (i < words[n].length() && words[n].charAt(i) == S.charAt(j)) {
i++;
}
//否则的话,当前word的char != S的当前word char, 需要判断,当前S的char 和前一个以及后一个 是否相等。如果相等,则跳过当前char, 在for里面回跳过下一个char,进而将S的指针向后移动。
else if (j > 0 && S.charAt(j) ==S.charAt(j-1) && j + 1 < S.length() && S.charAt(j) == S.charAt(j+1)){
j++;
}
//如果S的当前char 不等于 前一个或者前两个,则直接跳过该单词。
else if (!(j > 1 && S.charAt(j) ==S.charAt(j-1) && S.charAt(j) ==S.charAt(j-2))){
break;
}
}
if (i == words[n].length() && j == S.length()) // both pointers reach the end
res++;
}
}
return res;
}
}