[LeetCode] 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
Note:
- All the given strings‘ lengths will not exceed 10.
- The length of the given list will be in the range of [2, 50].
題意:找出一個字符串數組中最長的特殊字符串
特殊字符串指的是,它不是任何非它的子序列串,子序列串就不解釋了
其一,如果一個字符串的長度大於另一個字符串,那麽它一定不是另一個的子序列串,
其二,我們找到最長的那個可以從最長的開始判斷。
所以綜上兩點,我們可以想到對其先排序,從大到小按照字符串的長度,但是有個問題,如果是等長的,那麽所有和它等長的我們都需要去判斷,
所以我們需要維護一個數組,其中包含了需要和當前元素判斷的數組
class Solution { private boolean ifSubString(String parent, String sub) {int i = 0; int j = 0; while (i < parent.length() && j < sub.length()) { if (parent.charAt(i) == sub.charAt(j)) { i++; j++; } else i++; } if (j >= sub.length()) return true; return false; } public int findLUSlength(String[] strs) { if (strs.length == 0) return 0; Map<Integer, ArrayList<String>> map = new TreeMap<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (o1.intValue() > o2.intValue()) return -1; if (o1.intValue() < o2.intValue()) return 1; return 0; } }); for (int i = 0; i < strs.length; i++) { int lth = strs[i].length(); if (map.containsKey(lth)) { ArrayList list = map.get(lth); list.add(strs[i]); map.put(lth, list); } else { ArrayList<String> list = new ArrayList<>(); list.add(strs[i]); map.put(lth, list); } } ArrayList<String> res = new ArrayList<>(); for (Map.Entry entry : map.entrySet()) { ArrayList<String>list = (ArrayList) entry.getValue(); for (int i = 0; i < list.size(); i++) res.add(list.get(i)); if (res.size() == 1) return res.get(0).length(); for (int i = 0; i < res.size(); i++) { boolean flag = true; for (int j = 0; j < res.size(); j++) { if (i == j) continue; if (ifSubString(res.get(j), res.get(i))) { flag = false; break; } } if (flag) return (int) entry.getKey(); } } return -1; } }
[LeetCode] 522. Longest Uncommon Subsequence II