This approach takes advantage of the fact that if two strings are identical, there are no uncommon subsequences. If they are different, the longest uncommon subsequence is the longest string itself.
a
is equal to b
, return -1 because all subsequences of a
are subsequences of b
and vice versa.a
is not equal to b
, return the maximum length of a
or b
since the longer string itself cannot be a subsequence of the other.Time Complexity: O(n) where n is the length of the strings, due to the string comparison.
Space Complexity: O(1), no additional space is needed.
1public class Main {
2 public static int findLUSlength(String a, String b) {
3 return a.equals(b) ? -1 : Math.max(a.length(), b.length());
4 }
5 public static void main(String[] args) {
6 String a = "aba";
7 String b = "cdc";
8 System.out.println(findLUSlength(a, b));
9 }
10}
This Java solution uses the equals
method to determine if the string contents are the same and Math.max
to find the longer string if they are not.
Another approach is to analyze the problem by considering the entire strings as potential subsequences and determine their existence in the other string.
Time Complexity: O(n + m) where n and m are the lengths of the strings.
Space Complexity: O(1), since no additional structures are employed.
1public class Main {
2 public static boolean isSubsequence(String s, String t) {
3 int i = 0, j = 0;
4 while (i < s.length() && j < t.length()) {
5 if (s.charAt(i) == t.charAt(j)) i++;
6 j++;
7 }
8 return i == s.length();
9 }
10 public static int findLUSlength(String a, String b) {
11 if (isSubsequence(a, b) || isSubsequence(b, a)) return -1;
12 return Math.max(a.length(), b.length());
13 }
14 public static void main(String[] args) {
15 String a = "aba";
16 String b = "cdc";
17 System.out.println(findLUSlength(a, b));
18 }
19}
This Java solution implements a helper method isSubsequence
to check subsequence relations between a
and b
string pairs.