Leetcode 522. Longest Uncommon Subsequence II
Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence which is not a subsequence of any other string in the list.
A subsequence can be derived from another string by deleting some characters without changing the order of the remaining characters.
Example:
Input: ["aba", "cdc", "eae"]
Output: 3
In this example, “aba” is not a subsequence of “cdc” or “eae”, and similarly for others. Therefore, any of the strings count as the longest uncommon subsequence and its length is 3.
If no such subsequence exists, return -1.
The key idea is to leverage the following approach:
To determine if a string is a subsequence of another string, use two pointers for comparison.
Let’s write the Java code to solve the problem:
import java.util.*;
public class Solution {
// Helper function to determine if `s1` is a subsequence of `s2`
private boolean isSubsequence(String s1, String s2) {
int i = 0;
for (int j = 0; j < s2.length() && i < s1.length(); j++) {
if (s1.charAt(i) == s2.charAt(j)) {
i++;
}
}
return i == s1.length();
}
public int findLUSlength(String[] strs) {
// Sort the strings by their lengths in descending order
Arrays.sort(strs, (a, b) -> b.length() - a.length());
for (int i = 0; i < strs.length; i++) {
boolean isUncommon = true;
for (int j = 0; j < strs.length; j++) {
if (i != j && isSubsequence(strs[i], strs[j])) {
isUncommon = false;
break;
}
}
if (isUncommon) {
return strs[i].length();
}
}
return -1;
}
public static void main(String[] args) {
Solution solution = new Solution();
String[] strs = {"aba", "cdc", "eae"};
System.out.println(solution.findLUSlength(strs)); // Output: 3
}
}
Thus, the overall time complexity is O(n log n + n^2 * l).
Space complexity is O(1) for extra variables, not considering the space used by the input data.
If you have any further questions or need clarifications, feel free to ask!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?