做一道新题。
Example 1:
Input: arr = [“un”,“iq”,“ue”]
Output: 4
Explanation: All possible concatenations are “”,“un”,“iq”,“ue”,“uniq” and “ique”.
Maximum length is 4.
图转自花花酱
用bitmask
class Solution {
int max = 0;
public int maxLength(List<String> arr) {
List<Integer> list = new LinkedList<Integer>();
for(String a: arr){
int curMask = 0;
for(int i = 0; i < a.length(); i++){
curMask = curMask | (1 << a.charAt(i) -'a');
}
if(Integer.bitCount(curMask) != a.length())
continue;
list.add(curMask);
}
helper(list, 0, 0);
return max;
}
public void helper(List<Integer> list, int n, int mask){
int count = Integer.bitCount(mask);
max = Math.max(count, max);
for(int i = n; i < list.size(); i++){
if((mask & list.get(i)) == 0)
{
helper(list, i + 1, mask | list.get(i));
}
}
}
}
用set做也可以
class Solution {
int max = 0;
public int maxLength(List<String> arr) {
if(arr == null)
return 0;
helper(arr, "", 0);
return max;
}
public void helper(List<String> arr, String path, int n){
max = Math.max(max, path.length());
for(int i = n; i < arr.size(); i++){
if(isUnique(path + arr.get(i))){
helper(arr, path + arr.get(i), i + 1);
}
}
}
public boolean isUnique(String path){
HashSet<Character> set = new HashSet<Character>();
for(int i = 0; i < path.length(); i++){
if(set.contains(path.charAt(i)))
return false;
set.add(path.charAt(i));
}
return true;
}
}
总结
- 先把string转成bitmask
- Integer.bitCount()求1的个数