原题链接在这里:https://leetcode.com/problems/k-similar-strings/
题目:
Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.
Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.
Example 1:
Input: s1 = "ab", s2 = "ba" Output: 1
Example 2:
Input: s1 = "abc", s2 = "bca" Output: 2
Constraints:
1 <= s1.length <= 20s2.length == s1.lengths1ands2contain only lowercase letters from the set{'a', 'b', 'c', 'd', 'e', 'f'}.s2is an anagram ofs1.
题解:
The smallest swap, we could use BFS.
For a current string, if cur.equals(s2), return returns current level.
If not, we get all its neighbors.
To get a neighbor, we first find the different char between cur and s2, mark its index as ind.
Then find the next char where cur.charAt(j) == s2.charAt(ind).
Time Complexity: O(k*n^2). n = s1.length(). k = swap count, could be up to n. There could be k level BFS iteration. In each iteration, for each cur, we could find n neighbor, totally there could be n node in the que, thus there are n^2 neighbors.
Space: O(n^2).
AC Java:
1 class Solution {
2 public int kSimilarity(String s1, String s2) {
3 LinkedList<String> que = new LinkedList<>();
4 HashSet<String> visited = new HashSet<>();
5 que.add(s1);
6 visited.add(s1);
7 int level = 0;
8
9 while(!que.isEmpty()){
10 int size = que.size();
11 while(size-- > 0){
12 String cur = que.poll();
13 if(cur.equals(s2)){
14 return level;
15 }
16
17 for(String can : getNei(cur, s2)){
18 if(visited.contains(can)){
19 continue;
20 }
21
22 que.add(can);
23 visited.add(can);
24 }
25 }
26
27 level++;
28 }
29
30 return -1;
31 }
32
33 private List<String> getNei(String s1, String s2){
34 char [] s1Arr = s1.toCharArray();
35 char [] s2Arr = s2.toCharArray();
36 int n = s1.length();
37 int ind = 0;
38 while(ind < n && s1Arr[ind] == s2Arr[ind]){
39 ind++;
40 }
41
42 List<String> res = new ArrayList<>();
43 for(int j = ind + 1; j < n; j++){
44 if(s1Arr[j] == s2Arr[j] || s1Arr[j] != s2Arr[ind]){
45 continue;
46 }
47
48 swap(s1Arr, ind, j);
49 res.add(new String(s1Arr));
50 swap(s1Arr, ind, j);
51 }
52
53 return res;
54 }
55
56 private void swap(char [] arr, int i, int j){
57 char temp = arr[i];
58 arr[i] = arr[j];
59 arr[j] = temp;
60 }
61 }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/282809.html