522. Longest Uncommon Subsequence II

来源:互联网 发布:工业大数据 质量管理 编辑:程序博客网 时间:2024/06/04 18:58

522. Longest Uncommon Subsequence II

  • 题目描述: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
  • 题目大意,找出给定序列中的最长非公共子序列

  • 思路:对序列中的字符按长度进行排序,如果序列不重复则最长序列的长度就是所需的答案,否则如果最长字符串不是所需的答案,则比较其他字符串,但是较小字符串可能是较大字符串的子序列,所以需要判断,较小字符是不是较大字符的子序列,如果不是,则是我们要找的答案

  • 代码

    package String;import java.util.*;/*** @Author OovEver* @Date 2017/12/8 18:22*/public class LeetCode522 {  public int findLUSlength(String[] strs) {      Arrays.sort(strs, new Comparator<String>() {          @Override          public int compare(String o1, String o2) {              return o2.length() - o1.length();          }      });      Set<String> duplicates = getDuplicates(strs);      for(int i=0;i<strs.length;i++) {          if (!duplicates.contains(strs[i])) {              if (i == 0) {                  return strs[0].length();              }              for(int j=0;j<i;j++) {                  if (isSubsequence(strs[j], strs[i])) {                      break;                  }                  if(j == i-1) return strs[i].length();              }          }      }      return -1;  }  private boolean isSubsequence(String a, String b) {      int i = 0, j = 0;      while (i < a.length() && j < b.length()) {          if (a.charAt(i) == b.charAt(j)) {              j++;          }          i++;      }      return j == b.length();  }  private Set<String> getDuplicates(String[] strs) {      Set<String> set = new HashSet<>();      Set<String> duplicates = new HashSet<>();      for (String s : strs) {          if(set.contains(s)) duplicates.add(s);          set.add(s);      }      return duplicates;  }  public static void main(String[] args) {  }}
原创粉丝点击