[LeetCode]522. Longest Uncommon Subsequence II

来源:互联网 发布:电子线路板设计软件 编辑:程序博客网 时间:2024/06/05 20:12

https://leetcode.com/problems/longest-uncommon-subsequence-ii/#/description

给一组字符串,找出最长不相同子序列(子序列是保证相对位置不变,子字符串是保证相邻且顺序不变),如果不存在就返回-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;    }}