题目描述
如果可以通过将 A 中的两个小写字母精确地交换位置 K 次得到与 B 相等的字符串,我们称字符串 A 和 B 的相似度为 K(K 为非负整数)。
给定两个字母异位词 A 和 B ,返回 A 和 B 的相似度 K 的最小值。
- 输入:A = “ab”, B = “ba”
输出:1 - 输入:A = “ab”, B = “ba”
输出:1 - 输入:A = “abac”, B = “baca”
输出:2 - 输入:A = “aabc”, B = “abca”
输出:2 - 提示:
1 <= A.length == B.length <= 20
A 和 B 只包含集合 {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’} 中的小写字母。
这个题不做过多解释了,因为太晚了~~~
采用BFS,详情请看代码
class Solution {
public int kSimilarity(String A, String B) {
int i = 0;
int len = B.length();
for(i = 0;i<A.length();i++){
if(A.charAt(i)!=B.charAt(i))
break;
}//找出第一个不相符的位置
Queue<Pair> queue = new LinkedList<Pair>();
queue.offer(new Pair(A,i));
Set<String> set = new HashSet<>();
set.add(A);
int res = 0;
while(!queue.isEmpty()){
int n = queue.size();
for(int k = 0;k<n;k++){//遍历第res次交换后的字符串
int index = queue.peek().f;
String str = queue.peek().s;
queue.poll();
if(str.equals(B))
return res;
while(index<len&&str.charAt(index)==B.charAt(index))
index++;
/*if(index==len)
return res;*/
for(int j = index+1;j<len;j++){//对每一个字符串的子字符串入队操作
if(str.charAt(j)==B.charAt(index)&&str.charAt(j)!=B.charAt(j)){
str = swap(str,index,j);
if(!set.contains(str)){
queue.offer(new Pair(str,index+1));
set.add(str);
}
str = swap(str,index,j);
}
}
}
res++;
}
return res;
}
public String swap(String m,int a,int b){
StringBuilder sb = new StringBuilder();
sb.append(m.substring(0,a)).append(m.substring(b,b+1)).append(m.substring(a+1,b)).append(m.substring(a,a+1)).append(m.substring(b+1));
return sb.toString();
}
class Pair{
String s;
int f;
public Pair(String t,int d){
s = t;
f = d;
}
}
}