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 charactersc
, and add some number of the same characterc
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 in
words
consist only of lowercase lettersclass Solution {
public int expressiveWords(String S, String[] words) {
if (S == null || S.length() == 0 || words == null) return 0;
List<String> sourceGroups = breakStr(S);
int ans = 0;
for (String word : words){
List<String> targetGroups = breakStr(word);
if (valid(sourceGroups, targetGroups)) ans++;
}
return ans;
}
private boolean valid(List<String> sourceGroups, List<String> targetGroups){
if (sourceGroups.size() != targetGroups.size()) return false;
for (int i = 0; i < sourceGroups.size(); i++){
String str1 = sourceGroups.get(i);
String str2 = targetGroups.get(i);
if (str1.charAt(0) != str2.charAt(0) || str1.length() < str2.length() || (str1.length() > str2.length() && str1.length() < 3)) return false;
}
return true;
}
private List<String> breakStr(String s){
List<String> ans = new ArrayList<>();
int start = 0;
while (start < s.length()){
char c = s.charAt(start);
int end = start + 1;
while (end < s.length() && s.charAt(end) == c){
end++;
}
ans.add(s.substring(start, end));
start = end;
}
return ans;
}
}