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 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步