Thursday, December 27, 2018

809. Expressive Words




52.66 %
class Solution {
    public int expressiveWords(String S, String[] words) {
        if (S == null || S.length() == 0 || words == null || words.length == 0) return 0;
int result = 0;
for (String word : words) {
if (check(S, word)) result++;
}
return result;
}
private boolean check(String S, String word) {
int pw = 0; // pointer of char position in word
for (int i = 0; i < S.length();) {
// Assume previous substring has already been matched
if (pw >= word.length() || S.charAt(i) != word.charAt(pw)) return false;
int countS = 1, countW = 1;
while (i + countS < S.length() && S.charAt(i + countS) == S.charAt(i)) countS++;
while (pw + countW < word.length() && word.charAt(pw + countW) == S.charAt(i)) countW++;
if (countS < countW) return false;
// countS >= 3 we can expand
if (countS != countW && countS < 3) return false;
pw += countW;
i += countS;
}
return pw == word.length();
}
}

No comments:

Post a Comment