【华为OD题库-073】字符串变换最小字符串-java

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

示例3

输入:

acdebf

输出:

abdecf

说明:

a的位置已经是最小了,就确定下一个位置c是不是最小,显而易见不是最小,最小是b,将c与b替换

 java代码

package odTest;

import java.util.Arrays;
import java.util.Scanner;

public class minStr {
	
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
	    char[] strList = scanner.nextLine().toCharArray();
	    
	    int minIndex = 0;
	    int objectIndex = 0;
	    String[] objectStr = judgeMinStr(strList,minIndex,objectIndex).split(" ");
        if(!objectStr[0].equals(objectStr[1])) {
        	char objectCharVa = strList[Integer.parseInt(objectStr[1])];
        	char minCharVa = strList[Integer.parseInt(objectStr[0])];
        	strList[Integer.parseInt(objectStr[1])] = minCharVa;
        	strList[Integer.parseInt(objectStr[0])] = objectCharVa;
        }
        System.out.println(String.valueOf(strList));
        
	}

	private static String judgeMinStr(char[] strList, int minIndex, int objectIndex) {
		for(int i=objectIndex;i<strList.length;i++) {
			if(strList[minIndex]>strList[i]) {
				minIndex = i;
			}
			if(i==strList.length-1&&minIndex==objectIndex) {
				return judgeMinStr(strList,minIndex+1,objectIndex+1);
			}else if(i==strList.length-1){
				return minIndex+" "+objectIndex;
			}
		}
		return minIndex+" "+objectIndex;
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值