-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path22. Longest Word in Dictionary through Deleting
46 lines (42 loc) · 1.41 KB
/
22. Longest Word in Dictionary through Deleting
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
class Solution {
public String findLongestWord(String s, List<String> d) {
String result = "";
d.sort((String a, String b) ->
a.length() == b.length() ? a.compareTo(b) : b.length() - a.length());
for(String str : d) {
if(isSubsequence(s, str)) return result = str;
}
return result;
}
public boolean isSubsequence(String S, String D) {
int i = 0, j = 0;
if(D.length() > S.length()) return false;
while(i < S.length() && j < D.length()) {
if(S.charAt(i) == D.charAt(j)) j++;
i++;
}
return j == D.length();
}
}
class Solution {
public String findLongestWord(String s, List<String> d) {
String result = "";
for(String str : d) {
if(isSubsequence(s, str) ) {
//Length str > result || length is equal but str is lexicographically small.
if(str.length() > result.length() || (str.length() == result.length() && str.compareTo(result) < 1))
result = str;
}
}
return result;
}
public boolean isSubsequence(String S, String D) {
int i = 0, j = 0;
if(D.length() > S.length()) return false;
while(i < S.length() && j < D.length()) {
if(S.charAt(i) == D.charAt(j)) j++;
i++;
}
return j == D.length();
}
}