Leetcode 521. Longest Uncommon Subsequence I
Given two strings a
and b
, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence doesn’t exist, return -1.
An uncommon subsequence is a subsequence that is a substring of one of the strings but not a substring of the other.
a
and b
?
a
and b
will be between 1 and 100 inclusive.a
and b
be the same?
a
and b
can be the same string.a
and b
are equal?
a
and b
are equal, return -1
because there will be no uncommon subsequence.a
and b
are equal.
a == b
, return -1
because there’s no uncommon subsequence.a
and b
are not equal, the longest uncommon subsequence would simply be the longer string itself.
a
(or b
) cannot be a subsequence of the other string unless they are identical, which we already checked for.O(1)
.#include <iostream>
#include <string>
#include <algorithm>
int findLUSlength(std::string a, std::string b) {
if (a == b)
return -1;
return std::max(a.length(), b.length());
}
int main() {
std::string a = "abc";
std::string b = "cdc";
std::cout << findLUSlength(a, b) << std::endl; // Output: 3
a = "aaa";
b = "bbb";
std::cout << findLUSlength(a, b) << std::endl; // Output: 3
a = "abc";
b = "abc";
std::cout << findLUSlength(a, b) << std::endl; // Output: -1
return 0;
}
In the provided code, the findLUSlength
function implements the strategy described. It first checks if the two strings are equal and returns -1
if they are. If they are not equal, it returns the length of the longer string, which is the length of the longest uncommon subsequence.
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?