zoukankan      html  css  js  c++  java
  • 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:

    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:

     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 }

    类似Longest Uncommon Subsequence I.

  • 相关阅读:
    Emacs 安装 jedi
    PHP+ MongoDB
    Debian 7 安装 Emacs 24.3
    在Code first中使用数据库里的视图
    Emacs安装auto-complete
    Debian 7.4 中配置PHP环境
    ASP.NET MVC 下载列表
    JDicom使用指南
    Windows常用的DOS命令
    Entity Framework问题总结
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7052904.html
Copyright © 2011-2022 走看看