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:
public class Solution {
public int findLUSlength(String[] strs) {
if(strs == null || strs.length == 0){
return -1;
} HashMap<String, Integer> hm = new HashMap<String, Integer>();
for(String s : strs){
for(String subStr : getSubsequences(s)){
hm.put(subStr, hm.getOrDefault(subStr, 0)+1);
}
} int res = -1;
for(Map.Entry<String, Integer> entry : hm.entrySet()){
if(entry.getValue() == 1){
res = Math.max(res, entry.getKey().length());
}
}
return res;
} private HashSet<String> getSubsequences(String s){
HashSet<String> hs = new HashSet<String>(); if(s.length() == 0){
hs.add("");
return hs;
} HashSet<String> subHs = getSubsequences(s.substring(1));
hs.addAll(subHs);
for(String str : subHs){
hs.add(s.charAt(0)+str);
}
return hs;
}
}
类似Longest Uncommon Subsequence I.
最新文章
- 嵌入式 python异常except语句用法与引发异常 zz
- ListView条目的侧拉删除
- ASP.NET 缓存
- Segmetation fault你来的真不是时候
- CentOS下netstat + awk 查看tcp的网络连接状态
- for in
- 总结的Ubuntu的若干小知识
- Ouath协议
- hdu4741
- 虚拟主机,VPS,云主机之间的区别?
- SpringMVC归纳-2(Session会话、拦截器)
- JS所包含的大纲内容,以及JS中数据类型、运算符的介绍
- 关于 API
- sql server 高可用故障转移(5)
- Django cookie相关操作
- Zookeeper系列六:服务器角色、序列化与通信协议、数据存储、zookeeper总结
- mysqli字符编码
- 面向对象object与constructor
- [转帖] k8s kubectl 命令行技巧
- mybatis-generator生成逆向工程两种方式