854. 相似度为 K 的字符串

854. 相似度为 K 的字符串【LeetCode】

1.题目描述

对于某些非负整数 k ,如果交换 s1 中两个字母的位置恰好 k 次,
能够使结果字符串等于 s2 ,则认为字符串 s1 和 s2 的 相似度为 k 。

给你两个字母异位词 s1 和 s2 ,返回 s1 和 s2 的相似度 k 的最小值。

示例 1:

输入:s1 = "ab", s2 = "ba"
输出:1

示例 2:

输入:s1 = "abc", s2 = "bca"
输出:2

提示:

    1 <= s1.length <= 20
    s2.length == s1.length
    s1 和 s2  只包含集合 {'a', 'b', 'c', 'd', 'e', 'f'} 中的小写字母
    s2 是 s1 的一个字母异位词



2.解题思路

本题LeetCode中hard级别,确实有点难想(自我安慰下)。

首先,题目已经说明s1与s2互为字母异位词,说明s2通过交互字母是一定可以与s1相同的。

以下为图解分析:

在这里插入图片描述
因此,本文要考虑使用回溯+剪枝的方法。

回溯法目的:通过遍历所有的可能交互结果,获得最小的交互次数。
剪枝:减少寻找的时间,省去不必要的交互。

3.代码


  //回溯+剪枝
    int result = Integer.MAX_VALUE;
    public int kSimilarity2(String s1, String s2) {
        return execute(s1.toCharArray(), s2.toCharArray(), 0, 0);
    }

    public int execute(char[] sc1, char[] sc2, int start, int current) {
        if (current >= result) return result; // 如果交换次数已经超过"目前最小交换次数result",终止递归
        if (start == sc1.length - 1) return result = Math.min(current, result);//遍历结束,返回最小结果

        for (int i = start; i < sc1.length; i++) {
            if (sc1[i] != sc2[i]) {//判断是否进行交换
                for (int j = i + 1; j < sc2.length; j++) {
                    if (sc2[j] == sc1[i] && sc2[j] != sc1[j]) {//优化,避免多余的交换
                        swap1(sc2, i, j); // 交换
                        execute(sc1, sc2, i + 1, current + 1);//进行递归操作,每次交换完成后,向后移动,继续进行判断,同时记录交换的次数
                        swap1(sc2, i, j); // 回溯
                        //if (sc2[i] == sc1[j]) break; // 如果sc1和sc2的i位于j位互为相等,那么就是最优交换
                    }
                }
                return result;
            }
        }
        return result = Math.min(current, result);
    }

    public void swap1(char[] sc, int i, int j){
        char temp = sc[i];
        sc[i] = sc[j];
        sc[j] = temp;
    }

链接: 854. 相似度为 K 的字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值