题目描述;
对于某些非负整数 k ,如果交换 s1 中两个字母的位置恰好 k 次,能够使结果字符串等于 s2 ,则认为字符串 s1 和 s2 的 相似度为 k 。
给你两个字母异位词 s1 和 s2 ,返回 s1 和 s2 的相似度 k 的最小值。
Level | AC rate |
Hard | 44.8% |
题目解析:
首先说一下我自己的解法,我先将各个字符对应字符串中的位置用哈希表进行存储,我从左往右遍历,直到s1和s2对应位置的字母不匹配则进行选择, 若存在交换过后能够同时满足两处的字母都相等则优先考虑,如果没有则交换最后一个,然后用一个vis数组来存储目前字符串的访问状态,如果为true表明已经交换好了,不再进行操纵,之所以用这个数组是为了减去哈希表的删除操作,代码如下:
class Solution {
HashMap<Character,List<Integer>> map;
String str1;
String str2;
int ans = 0;
boolean[] vis;
public int kSimilarity(String s1, String s2) {
map = new HashMap<Character,List<Integer>>();
if(s1.length()==1)return 0;
str1=s1;
str2=s2;
vis = new boolean[str2.length()];
for(int i = 0 ; i<str2.length() ; i++){
char cur = str2.charAt(i);
if(str1.charAt(i)==str2.charAt(i))vis[i] = true;
if(map.containsKey(cur))map.get(cur).add(i);
else{
List<Integer> temp = new ArrayList<Integer>();
temp.add(i);
map.put(cur,temp);
}
}
for(int i = 0 ; i<s1.length() ; i++){
if(str1.charAt(i)==str2.charAt(i))continue;
else{
cal(i,str1.charAt(i),str2.charAt(i));
System.out.println(str2);
}
}
return ans;
}
void cal(int idx , char c1 , char c2){
List<Integer> temp = map.get(c1);
for(int i = 0 ; i<temp.size() ; i++){
if(vis[temp.get(i)]==true)continue;
if(str1.charAt(temp.get(i))==c2){
swap(idx,temp.get(i));
vis[idx] = true;
vis[temp.get(i)] = true;
map.get(c1).remove(i);
ans++;
break;
}
if(i==temp.size()-1){
int pos = temp.get(i);
swap(idx,pos);
map.get(c2).add(pos);
map.get(c1).remove(i);
vis[idx] = true;
ans++;
}
}
}
void swap(int pos1 , int pos2){
char[] str = str2.toCharArray();
char temp = str[pos2];
str[pos2] = str[pos1];
str[pos1] = temp;
str2 = String.valueOf(str);
}
}
对于某些测试用例不能够通过,但我感觉我想的没有什么问题,具体的之后再学吧,然后我们换了一种暴力求解的方法,通过for循环找出每一种交换的情况,来判断谁的所用步数最少即可,代码如下:
class Solution {
public int kSimilarity(String s1, String s2) {
Queue<Pair<String,Integer>> queue = new LinkedList<Pair<String,Integer>>();
Set<String> set = new HashSet<String>();
queue.offer(new Pair<String,Integer>(s1,0));
set.add(s1);
int step = 0;
while(!queue.isEmpty()){
int limit = queue.size();
for(int time = 0 ; time<limit ; time++){
Pair<String,Integer> pair = queue.poll();
String str = pair.getKey();
if(str.equals(s2))return step;
int pos = pair.getValue();
while(pos<s2.length()&&str.charAt(pos) == s2.charAt(pos)){
pos++;
}
for(int i = pos+1 ; i<s2.length() ; i++){
if(str.charAt(i)==s2.charAt(i))continue;
if(s2.charAt(pos)==str.charAt(i)){
String temp = swap(str,pos,i);
if(!set.contains(temp)){
queue.offer(new Pair<String,Integer>(temp,pos+1));
set.add(temp);
}
}
}
}
step++;
}
return 0;
}
String swap(String str , int pos1 , int pos2){
char[] ch = str.toCharArray();
char temp = ch[pos2];
ch[pos2] = ch[pos1];
ch[pos1] = temp;
return String.valueOf(ch);
}
}
唯一一点需要注意的是,需要将str情况下的所有交换方式得到的字符串都压进堆里再进行step++操作。
执行用时:28 ms, 在所有 Java 提交中击败了78.16%的用户
内存消耗:42.4 MB, 在所有 Java 提交中击败了55.75%的用户