LeetCode Longest Uncommon Subsequence II
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Longest Uncommon Subsequence II相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/longest-uncommon-subsequence-ii/#/description
题目:
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].
题解:
对每一个string取出所有可能的substring 放到同一个map里计数. 找出计数为1的最长substring长度.
Time Complexity: O(n * 2^k). n = strs.length, k 是longest string的长度. 每一个s有2^s.length()个substring.
Space: O(k). stack space.
AC Java:
1 public class Solution { 2 public int findLUSlength(String[] strs) { 3 if(strs == null || strs.length == 0){ 4 return -1; 5 } 6 7 HashMap<String, Integer> hm = new HashMap<String, Integer>(); 8 for(String s : strs){ 9 for(String subStr : getSubsequences(s)){ 10 hm.put(subStr, hm.getOrDefault(subStr, 0)+1); 11 } 12 } 13 14 int res = -1; 15 for(Map.Entry<String, Integer> entry : hm.entrySet()){ 16 if(entry.getValue() == 1){ 17 res = Math.max(res, entry.getKey().length()); 18 } 19 } 20 return res; 21 } 22 23 private HashSet<String> getSubsequences(String s){ 24 HashSet<String> hs = new HashSet<String>(); 25 26 if(s.length() == 0){ 27 hs.add(""); 28 return hs; 29 } 30 31 HashSet<String> subHs = getSubsequences(s.substring(1)); 32 hs.addAll(subHs); 33 for(String str : subHs){ 34 hs.add(s.charAt(0)+str); 35 } 36 return hs; 37 } 38 }
以上是关于LeetCode Longest Uncommon Subsequence II的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 521. Longest Uncommon Subsequence I
[LeetCode] 522. Longest Uncommon Subsequence II
LeetCode 521 Longest Uncommon Subsequence I 解题报告
LeetCode: 521 Longest Uncommon Subsequence I(easy)