522. Longest Uncommon Subsequence II
Description
Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.
An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.
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).
Example 1:
Input: strs = ["aba","cdc","eae"] Output: 3
Example 2:
Input: strs = ["aaa","aaa","aa"] Output: -1
Constraints:
2 <= strs.length <= 501 <= strs[i].length <= 10strs[i]consists of lowercase English letters.
Solutions
Solution 1: Subsequence Judgment
We define a function \(check(s, t)\) to determine whether string \(s\) is a subsequence of string \(t\). We can use a two-pointer approach, initializing two pointers \(i\) and \(j\) to point to the beginning of strings \(s\) and \(t\) respectively, then continuously move pointer \(j\). If \(s[i]\) equals \(t[j]\), then move pointer \(i\). Finally, check if \(i\) equals the length of \(s\). If \(i\) equals the length of \(s\), it means \(s\) is a subsequence of \(t\).
To determine if string \(s\) is unique, we only need to take string \(s\) itself and compare it with other strings in the list. If there exists a string for which \(s\) is a subsequence, then \(s\) is not unique. Otherwise, string \(s\) is unique. We take the longest string among all unique strings.
The time complexity is \(O(n^2 \times m)\), where \(n\) is the length of the list of strings, and \(m\) is the average length of the strings. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |