forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExpressive Words.java
73 lines (62 loc) · 2.01 KB
/
Expressive Words.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Solution {
private String getFreqString(String s) {
int len = s.length();
StringBuilder freqString = new StringBuilder();
int currFreq = 1;
char prevChar = s.charAt(0);
freqString.append(s.charAt(0));
for(int i = 1; i<len; i++) {
if(s.charAt(i) == prevChar) {
currFreq++;
} else {
freqString.append(currFreq);
freqString.append(s.charAt(i));
currFreq = 1;
}
prevChar = s.charAt(i);
}
if(currFreq>0) {
freqString.append(currFreq);
}
return freqString.toString();
}
private boolean isGreaterButLessThanThree(char sChar, char wChar) {
return sChar > wChar && sChar < '3';
}
private boolean isStretchy(String s, String word) {
int sLen = s.length();
int wordLen = word.length();
if(sLen != wordLen) {
return false;
}
for(int i = 0; i<sLen; i++) {
char sChar = s.charAt(i);
char wChar = word.charAt(i);
if(i%2 != 0) {
if(sChar < wChar) {
return false;
} if(isGreaterButLessThanThree(sChar, wChar)) {
return false;
}
} else if(sChar != wChar){
return false;
}
}
return true;
}
public int expressiveWords(String s, String[] words) {
int wordLen = words.length;
if(wordLen < 1 || s.length() < 1) {
return 0;
}
int stretchyWords = 0;
String freqStringS = getFreqString(s);
for(String word: words) {
String freqStringWord = getFreqString(word);
if(isStretchy(freqStringS, freqStringWord)) {
stretchyWords++;
}
}
return stretchyWords;
}
}