华为机试题-字符交换

文章讲述了如何通过一次字符交换操作,找到给定小写字母字符串的最小可能形式,以字典序排列。提供了Java代码实现该问题的解决方案。
摘要由CSDN通过智能技术生成
题目

给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较) 。
变换规则:交换字符串中任意两个不同位置的字符。
输入描述:
一串小写字母组成的字符串s
输出描述:
按照要求进行变换得到的最小字符串
备注:
s 是都是小写字符组成
1<=
1<= s.length
<=1000
<=1000
示例1
输入:
abcdef
输出:
abcdef
说明:
abcdef已经是最小字符串,不需要交换
示例2
输入:
bcdefa
输出:
acdefb
说明:
a 和 b 进行位置交换,可以得到最小字符串

参考代码
package RealTest;

/**
 * @ClassName MinStringAfterSwap
 * @Description TODO
 * @Author 21916
 * @Date 2024/3/18 14:19
 */

public class MinStringAfterSwap {
    public static String minString(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;

        // 遍历字符串中的每个字符
        for (int i = 0; i < n - 1; i++) {
            char currentChar = chars[i];
            int minIndex = i; // 记录从当前位置开始的最小字符的索引

            // 寻找从当前位置开始的最小字符及其索引
            for (int j = i + 1; j < n; j++) {
                if (chars[j] < currentChar) {
                    currentChar = chars[j];
                    minIndex = j;
                }
            }

            // 如果找到比当前字符更小的字符,则交换它们
            if (minIndex != i) {
                char temp = chars[i];
                chars[i] = chars[minIndex];
                chars[minIndex] = temp;
                // 因为已经找到了更优解并进行了交换,无需继续检查后面的字符
                break;
            }
        }

        // 将字符数组转换回字符串并返回
        return new String(chars);
    }

    public static void main(String[] args) {
        String s1 = "abcdef";
        System.out.println(minString(s1)); // 输出: abcdef

        String s2 = "bcdefa";
        System.out.println(minString(s2)); // 输出: acdefb
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@业精于勤荒于嬉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值