原题链接在这里: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:

  1. All the given strings' lengths will not exceed 10.
  2. 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.

最新文章

  1. 嵌入式 python异常except语句用法与引发异常 zz
  2. ListView条目的侧拉删除
  3. ASP.NET 缓存
  4. Segmetation fault你来的真不是时候
  5. CentOS下netstat + awk 查看tcp的网络连接状态
  6. for in
  7. 总结的Ubuntu的若干小知识
  8. Ouath协议
  9. hdu4741
  10. 虚拟主机,VPS,云主机之间的区别?
  11. SpringMVC归纳-2(Session会话、拦截器)
  12. JS所包含的大纲内容,以及JS中数据类型、运算符的介绍
  13. 关于 API
  14. sql server 高可用故障转移(5)
  15. Django cookie相关操作
  16. Zookeeper系列六:服务器角色、序列化与通信协议、数据存储、zookeeper总结
  17. mysqli字符编码
  18. 面向对象object与constructor
  19. [转帖] k8s kubectl 命令行技巧
  20. mybatis-generator生成逆向工程两种方式

热门文章

  1. Python 2 一些实用模块的使用
  2. loadrunner之脚本篇——代理录制
  3. c# 抽象类(abstract)
  4. 根据GUID获取设备信息
  5. $git学习总结系列(1)——基本用法
  6. OpenCV图片拼接的两种方法
  7. CSS3中新颖的布局方法
  8. JSP笔记03——环境搭建(转)
  9. curl扩展代码
  10. Win32 API编程:WinMain无法重载函数或_tWinMain无法重载