Skip to content

Commit fac10d2

Browse files
authored
Update Expressive Words.java
1 parent becfa84 commit fac10d2

File tree

1 file changed

+29
-44
lines changed

1 file changed

+29
-44
lines changed

Medium/Expressive Words.java

Lines changed: 29 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,32 @@
11
class Solution {
2-
public int expressiveWords(String S, String[] words) {
3-
int count = 0;
4-
char[] sChar = S.toCharArray();
5-
for (String word : words) {
6-
char[] wChar = word.toCharArray();
7-
if (check(sChar, wChar)) {
8-
count++;
9-
}
10-
}
11-
12-
return count;
13-
}
14-
15-
private boolean check(char[] s, char[] w) {
16-
int i = 0;
17-
int j = 0;
18-
19-
while (i < s.length && j < w.length) {
20-
if (s[i] != w[j]) {
21-
return false;
22-
}
23-
24-
int tempI = i;
25-
int tempJ = j;
26-
27-
while (i < s.length && s[i] == s[tempI]) {
28-
i++;
29-
}
30-
31-
while (j < w.length && w[j] == w[tempJ]) {
32-
j++;
33-
}
34-
35-
int l1 = i - tempI;
36-
int l2 = j - tempJ;
37-
38-
if (l1 == l2 || l1 >= 3 && l1 > l2) {
39-
continue;
40-
}
41-
42-
return false;
43-
}
44-
45-
return i == s.length && j == w.length;
2+
public int expressiveWords(String s, String[] words) {
3+
return (int) Arrays.stream(words).filter(word -> isExpressive(s, word)).count();
4+
}
5+
6+
private boolean isExpressive(String s, String word) {
7+
int sIdx = 0;
8+
int wordIdx = 0;
9+
while (sIdx < s.length() && wordIdx < word.length()) {
10+
if (s.charAt(sIdx) != word.charAt(wordIdx)) {
11+
return false;
12+
}
13+
char c1 = s.charAt(sIdx);
14+
int countC1 = 0;
15+
while (sIdx < s.length() && s.charAt(sIdx) == c1) {
16+
sIdx++;
17+
countC1++;
18+
}
19+
char c2 = word.charAt(wordIdx);
20+
int countC2 = 0;
21+
while (wordIdx < word.length() && word.charAt(wordIdx) == c2) {
22+
wordIdx++;
23+
countC2++;
24+
}
25+
if (countC1 == countC2 || (countC1 > countC2 && countC1 >= 3)) {
26+
continue;
27+
}
28+
return false;
4629
}
30+
return sIdx == s.length() && wordIdx == word.length();
31+
}
4732
}

0 commit comments

Comments
 (0)