赞
踩
给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较)。
变换规则:交换字符串中任意两个不同位置的字符。
1、对字符串按照字典序进行排序,找到字典序最小的字符串。
2、找到这个字符串中字典序最小的字符的位置。
3、找到字符串中第一个跟最小字符串不相同的字符的位置,然后跟第一个最小字符进行交换。
4、题目规定只能交换一次,交换后得到的就是最小字符串。
- function changeString(str) {
- let unSortStr = str.split('')
- let sortStr = str.split('').sort()
- let minStr = sortStr[0] , place = 0 , change = 0
- for(let i = 0 ; i < unSortStr.length ; i++) {
- if(unSortStr[i] == minStr) {
- place = i
- break
- }
- }
- for(let j = 0 ; j < unSortStr.length ; j++) {
- if(unSortStr[j] != minStr) {
- change = j
- break
- }
- }
- if(place>change) {
- swap(unSortStr,place,change)
- }
- return unSortStr.join('')
- //用于交换字符的函数
- function swap(arr,i,j) {
- let temp = arr[i]
- arr[i] = arr[j]
- arr[j] = temp
- }
- }
-
- console.log(changeString('bcacdef')) //打印结果:acbcdef
- console.log(changeString('abcdef')) //打印结果:abcdef

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。