1、在一个字符串中查找另外一个字符串任意的全排列出现位置。例如:A=”abcfsfcba”,B=”abc”,则返回{0,6}。
//the des's character must be adjacent
public static List<Integer> getIndex(String res,String des){
List<Integer> list=new ArrayList<>();
HashMap<Character,Integer> map=new HashMap<Character, Integer>();
int desLen=des.length();
int resLen=res.length();
for(int i=0;i<desLen;i++){
map.put(des.charAt(i), map.getOrDefault(des.charAt(i), 0)+1);
}
HashMap<Character,Integer> cur=new HashMap<Character, Integer>();
for(int i=0;i<=resLen-desLen;i++){
if(map.containsKey(res.charAt(i))){
cur.clear();
for(int j=0;j<desLen;j++){
if(map.containsKey(res.charAt(i+j)))
cur.put(res.charAt(i+j), cur.getOrDefault(res.charAt(i+j), 0)+1);
else break;
if(cur.get(res.charAt(i+j))>map.get(res.charAt(i+j)))break;
}
if(map.equals(cur))list.add(i);
}
}
return list;
}
2、在一个字符串中查找包含另外一个字符串任意全排列的长度最小的字符串。例如:A=”abdcgfgfabbbc”,B=“abc”,A中包含B的子字符串有“abdc”和“abbbc”,最短的则返回“abdc”。
// get the min length string in res which contains des
public static String getSting(String res, String des) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int desLen = des.length();
int resLen = res.length();
for (int i = 0; i < desLen; i++) {
map.put(des.charAt(i), map.getOrDefault(des.charAt(i), 0) + 1);
}
HashMap<Character, Integer> cur = new HashMap<Character, Integer>();
int start = -1, count = 0;
String val = res;
for (int i = 0; i < resLen; i++) {
if (map.containsKey(res.charAt(i))) {
if (start == -1)start = i;
cur.put(res.charAt(i), cur.getOrDefault(res.charAt(i), 0) + 1);
if (cur.get(res.charAt(i)) <= map.get(res.charAt(i)))count++;
if (count == desLen) {
//move from start pos,pass the multiple character
while (!map.containsKey(res.charAt(start))|| cur.get(res.charAt(start)) > map.get(res.charAt(start))) {
if (cur.getOrDefault(res.charAt(start), 0) > map.getOrDefault(res.charAt(start), 0)) {
cur.put(res.charAt(start),cur.get(res.charAt(start)) - 1);
}
start++;
}
// compare to get the min string
val = val.length() > (i - start + 1) ? res.substring(start,i + 1) : val;
}
}
}
// no match string
if (start > 0 && res.equals(val))return "";
return val;
}