Longest Uncommon Subsequence II

Similar Problems:

- Longest Uncommon Subsequence I
- CheatSheet: Leetcode For Code Interview
- Tag: #backtracking, #subsequence

Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn’t exist, return -1.

Example 1:

Input: "aba", "cdc", "eae" Output: 3

Note:

- All the given strings’ lengths will not exceed 10.
- The length of the given list will be in the range of [2, 50].

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

// https://code.dennyzhang.com/longest-uncommon-subsequence-ii // Basic Ideas: backtracking // // Evaluate all possiblities // Similar problem: Leetcode: Subsets II // // Complexity: Time O(50*pow(2, 10)), Space O(50*pow(2, 10)) func dfs(pos int, combination []byte, str string, m map[string]int) { // don't take current node if len(combination) != 0 { combination2 := make([]byte, len(combination)) copy(combination2, combination) m[string(combination2)]++ } // take current node for i:=pos; i<len(str); i++ { combination = append(combination, str[i]) dfs(i+1, combination, str, m) combination = combination[0:len(combination)-1] } } func findLUSlength(strs []string) int { m := map[string]int{} for _, str := range strs { dfs(0, []byte{}, str, m) } res := -1 for k, v := range m { if v == 1 { if len(k) > res { res = len(k) } } } return res }