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 <= 20
  • s2.length == s1.length
  • s1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.
  • s2 is an anagram of s1.

思路:就是BFS,每个level去搜,比较两个string,找到第一个不同的,ab, ba,第一个a必须换成b,那么就在s1里面找所有的b,然后生成下一层的string,记得swap回来;

class Solution {
    public int kSimilarity(String s1, String s2) {
        Queue<String> queue = new LinkedList<>();
        queue.offer(s1);
        
        int step = 0;
        HashSet<String> visited = new HashSet<>();
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                String node = queue.poll();
                if(node.equals(s2)) {
                    return step;
                }
                
                char[] ss = node.toCharArray();
                char[] ss2 = s2.toCharArray();
                int j = 0;
                for(; j < ss.length; j++) {
                    if(ss[j] != ss2[j]) {
                        break;
                    }
                }
                
                for(int k = j + 1; k < ss.length; k++) {
                    if(ss[k] == ss2[j]) {
                        // swap k, j;
                        swap(ss, k, j);
                        String newstr = new String(ss);
                        if(!visited.contains(newstr)) {
                            visited.add(newstr);
                            queue.offer(newstr);
                        }
                        // swap back;
                        swap(ss, k, j);
                    }
                }
            }
            step++;
        }
        return -1;
    }
    
    private void swap(char[] ss, int i, int j) {
        char temp = ss[i];
        ss[i] = ss[j];
        ss[j] = temp;
    }
}

### Nearest Algorithm or Implementation in Programming In programming, the concept of 'nearest' is often associated with algorithms that deal with proximity or similarity between data points. One common application involves finding the nearest neighbor within a set of points based on some distance metric such as Euclidean distance. A widely used approach for this purpose includes **k-nearest neighbors (KNN)** which falls under supervised learning methods where it can be applied both to classification and regression tasks [^2]. For instance: - In classification problems using KNN, an object's class membership is determined by majority voting among its k closest training samples. Another relevant area could involve string matching techniques like Levenshtein Distance calculation when considering textual differences; however specific implementations depend heavily upon context including language choice etcetera but generally follow similar principles regarding measuring closeness/distance metrics appropriately adjusted according domain requirements whether numerical vectors spaces strings sequences et cetera . Here’s how you might implement basic version knn classifier python utilizing euclidian distances : ```python import numpy as np def classify_knn(data_points , query_point,k=3): """Classify new point via KNN.""" distances = [] for index,point in enumerate(data_points): dist=np.linalg.norm(np.array(point)-np.array(query_point)) distances.append((dist,index)) sorted_distances=sorted(distances,key=lambda x:x[0]) top_indices=[i for d,i in sorted_distances[:k]] classes=[data_points[i][1]for i in top_indices ] prediction=max(set(classes),key=classes.count) return prediction ``` This function takes list tuples form `(feature_vector,label)` pairs alongside single feature vector representing unknown sample whose category needs estimating through comparison against known instances stored inside `data_points`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值