1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class Solution { public int expressiveWords(String s, String[] words) { int expressiveWords = 0;
for (String word : words) { if (match(s, word)) { expressiveWords++; } }
return expressiveWords; }
private boolean match(String s, String word) { int i = 0, j = 0; while (i < s.length() && j < word.length()) { if (s.charAt(i) != word.charAt(j)) { return false; }
int nextI = i; while (nextI < s.length() && s.charAt(nextI) == s.charAt(i)) { nextI++; } int exceptedCount = nextI - i;
int nextJ = j; while (nextJ < word.length() && word.charAt(nextJ) == word.charAt(j)) { nextJ++; } int actualCount = nextJ - j;
if (exceptedCount < actualCount) { return false; }
i = nextI; j = nextJ;
if (exceptedCount == actualCount) { continue; } if (exceptedCount == 2) { return false; } }
return i == s.length() && j == word.length(); } }
|
注意指针移动细节,注意 word 需要被匹配完而不仅仅是把 s 匹配完。
References
809. Expressive Words