题目:
给定一个字符串数组 arr
,字符串 s
是将 arr
的含有 不同字母 的 子序列 字符串 连接 所得的字符串。
请返回所有可行解 s
中最长长度。
子序列 是一种可以从另一个数组派生而来的数组,通过删除某些元素或不删除元素而不改变其余元素的顺序。
示例 1:
输入:arr = ["un","iq","ue"] 输出:4 解释:所有可能的串联组合是: - "" - "un" - "iq" - "ue" - "uniq" ("un" + "iq") - "ique" ("iq" + "ue") 最大长度为 4。
示例 2:
输入:arr = ["cha","r","act","ers"] 输出:6 解释:可能的解答有 "chaers" 和 "acters"。
示例 3:
输入:arr = ["abcdefghijklmnopqrstuvwxyz"] 输出:26
解题思路:采用HashSet的add方法加入不重复字母来比较两个字符串是否有重复,如果有重复,则大小与两个字符串和不等,反之则不重复。
代码如下:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Leetcode {
public static void main(String[] args) {
List<String> arr = new ArrayList<>();
arr.add("un");
arr.add("iq");
arr.add("ue");
System.out.println(maxLength(arr));
}
public static int maxLength(List<String> arr) {
List<HashSet<Character>> all = new ArrayList<>();
all.add(new HashSet<>());
int ans = 0;
for(String str : arr){
int allSize = all.size();
for(int i = 0;i < allSize;i++){
HashSet<Character> s = all.get(i);
HashSet<Character> temp = new HashSet<>(all.get(i));
int len = str.length();
for(int j = 0;j < len;j++){
temp.add(str.charAt(j));
}
if(temp.size() == s.size() + len){
all.add(temp);
ans = Math.max(ans,temp.size());
}
}
}
return ans;
}
}
运行结果如下:
时间复杂度已经达到O(N^3),优化方法暂时没想到...