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.

  • 相关阅读:
    初识 Mysql
    Python之协程
    crm 动态一级二级菜单
    admin 后台操作表格
    crm 权限设计
    crm 公户变私户的问题 班级管理 课程管理 学习记录初始化
    crm 添加用户 编辑用户 公户和私户的展示,公户和私户的转化
    crm 数据展示 和分页思想(一)
    python django(forms组件)
    python Django 中间件介绍
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7052904.html
Copyright © 2011-2022 走看看