Longest Uncommon Subsequence II LeetCode solution in Java

1
class Solution {
2
public int findLUSlength(String[] strs) {
3
Arrays.sort(strs, (a, b) -> b.length() - a.length()); // sort descending order by length
4
// store the frequency of all strings in array
5
Map<String, Integer> map = new HashMap<>();
6
for (String s : strs) map.put(s, map.getOrDefault(s, 0) + 1);
7

8
for (int i = 0; i < strs.length; i++) {
9
if (map.get(strs[i]) != 1) continue; // string is not unique
10
int j;
11
for (j = 0; j < i; j++) {
12
if (isSubsequence(strs[i], strs[j])) break;
13
}
14
// if it is not a subsequence of any other larger string
15
if (j == i) return strs[i].length();
16
}
17
return -1; // no string satisfies the criterion
18
}
19

20
public boolean isSubsequence(String a, String b) {
21
int i = 0, j = 0;
22
while (i < a.length() && j < b.length()) if (a.charAt(i) == b.charAt(j++)) i++;
23
return i == a.length();
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0