[LeetCode]522. Longest Uncommon Subsequence II
阿新 • • 發佈:2019-02-11
給一組字串,找出最長不相同子序列(子序列是保證相對位置不變,子字串是保證相鄰且順序不變),如果不存在就返回-1
找出所有字串的所有子序列,然後找裡面滿足要求的
public class Solution { public int findLUSlength(String[] strs) { HashMap<String, Integer> map = new HashMap(); for (String str : strs) { HashSet<String> set = getSubs(str); for (String s : set) { map.put(s, map.getOrDefault(s, 0) + 1); } } int res = -1; for (Map.Entry<String, Integer> e : map.entrySet()) { if (e.getValue() == 1) { res = Math.max(res, e.getKey().length()); } } return res; } private HashSet<String> getSubs(String s) { HashSet<String> res = new HashSet(); if (s.length() == 0) { res.add(""); } else { Set<String> set = getSubs(s.substring(1)); res.addAll(set); for (String str : set) { res.add(s.charAt(0) + str); } } return res; } }