串联字符串的最大长度–java–BFS
思路:
这道题可以使用BFS来做,前提是需要知道节点在集合中的位置。
代码:
```java
class Solution {
public int maxLength(List<String> arr) {
// bfs
Queue<Map<String,Integer>> queue = new LinkedList<Map<String,Integer>>();
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("",-1);
queue.add(map);
int res = 0;
while( !queue.isEmpty() ){
Map<String,Integer> temp = queue.remove();
String preStr = "";
for( String str : temp.keySet() ){
preStr = str;
}
res = preStr.length() > res ? preStr.length() : res;
for( int i = temp.values().toArray(new Integer[1])[0] + 1; i < arr.size(); ++i ){
if( isOk(preStr + arr.get(i)) ){
Map<String,Integer> newMap = new HashMap<>();
newMap.put(preStr + arr.get(i),i);
queue.add(newMap);
}
}
}
return res;
}
public boolean isOk(String str){
int ch[] = new int[26];
for( int i = 0; i < str.length(); ++i ){
int num = str.charAt(i) - 97;
++ch[num];
if( ch[num] > 1 ){
return false;
}
}
return true;
}
}