521. Longest Uncommon Subsequence I
Explanation
To solve this problem, we need to find the longest uncommon subsequence between two strings a
and b
. An uncommon subsequence is a subsequence of exactly one of the strings. If no such uncommon subsequence exists, we return -1.
We can observe that if the two strings a
and b
are different, then the longer string itself is the longest uncommon subsequence. If the strings are the same, then there is no uncommon subsequence as every subsequence of one string is also a subsequence of the other.
Therefore, we simply compare the strings. If they are the same, we return -1. Otherwise, we return the length of the longer string.
Time Complexity
The time complexity of this solution is O(max(a.length, b.length)), where a and b are the lengths of the input strings.
Space Complexity
The space complexity is O(1) as we are not using any extra space.
class Solution {
public int findLUSlength(String a, String b) {
if (a.equals(b)) {
return -1;
}
return Math.max(a.length(), b.length());
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.