Leetcode 521. Longest Uncommon Subsequence I
Given two strings a
and b
, return the length of the longest uncommon subsequence (LUS) between them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings that is not a subsequence of the other string.
A subsequence is a sequence derived from another sequence by deleting some or no elements without changing the order of the remaining elements. For example, “abc”, “ab”, and “a” are all subsequences of “abc”.
If the longest uncommon subsequence does not exist, return -1.
Example 1:
a = "aba"
, b = "cdc"
3
Example 2:
a = "aaa"
, b = "bbb"
3
Example 3:
a = "aaa"
, b = "aaa"
-1
a
and b
be empty?
a
and b
?
a
equals b
, then there is no uncommon subsequence, return -1.a
is not equal to b
, the longest uncommon subsequence will be the longer string itself because it won’t be a subsequence of the other string.public class Solution {
public int findLUSlength(String a, String b) {
if (a.equals(b)) {
return -1;
} else {
return Math.max(a.length(), b.length());
}
}
}
findLUSlength
function is O(N) where N is the maximum length of the strings a
or b
. This complexity arises from the equals
method which compares the two strings.if (a.equals(b))
: This checks if both strings are exactly the same.return Math.max(a.length(), b.length())
: This returns the length of the longer string as the longest uncommon subsequence. If the strings are of equal length but different, it returns that length, because neither string can be a subsequence of the other.By following this strategy, we ensure that we cover all cases effectively and efficiently.
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?