Categories:

Tags:



Problem

Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1.

An uncommon subsequence between two strings is a string that is a subsequence of one but not the other.

A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.

  • For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).

Constraints

  • 1 <= a.length, b.length <= 100
  • a and b consist of lower-case English letters.

Solution

The problem Longest Uncommon Subsequence I can be solved by comparing if strings a and b are equal. Let s be a subsequence of a. If s is also a subsequence of b, then there is no subsequence s' which is not a subsequence of b. In other words, if a and b are equal, a and b becomes subsequence for each other, and thus uncommon subsequence cannot exist. Conversely, if a and b are different and their lengths are the same, then both a and b becomes longest uncommon subsequence. Finally, if a and b are different and their lengths are also different, then the longer string becomes the longest uncommon subsequence. In short, if a and b are not the same, then the maximum value between two string lengths becomes the length of the longest uncommon subsequence.

Implementation

class Solution
{
  public:
    int findLUSlength(string a, string b) { return a == b ? -1 : max(a.length(), b.length()); }
};