当前位置:   article > 正文

字符串变换最小字符串

字符串变换最小字符串

题目:

给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较)。

变换规则:交换字符串中任意两个不同位置的字符。


解题思路:

1、对字符串按照字典序进行排序,找到字典序最小的字符串。

2、找到这个字符串中字典序最小的字符的位置。

3、找到字符串中第一个跟最小字符串不相同的字符的位置,然后跟第一个最小字符进行交换。

4、题目规定只能交换一次,交换后得到的就是最小字符串。

代码: 

  1. function changeString(str) {
  2. let unSortStr = str.split('')
  3. let sortStr = str.split('').sort()
  4. let minStr = sortStr[0] , place = 0 , change = 0
  5. for(let i = 0 ; i < unSortStr.length ; i++) {
  6. if(unSortStr[i] == minStr) {
  7. place = i
  8. break
  9. }
  10. }
  11. for(let j = 0 ; j < unSortStr.length ; j++) {
  12. if(unSortStr[j] != minStr) {
  13. change = j
  14. break
  15. }
  16. }
  17. if(place>change) {
  18. swap(unSortStr,place,change)
  19. }
  20. return unSortStr.join('')
  21. //用于交换字符的函数
  22. function swap(arr,i,j) {
  23. let temp = arr[i]
  24. arr[i] = arr[j]
  25. arr[j] = temp
  26. }
  27. }
  28. console.log(changeString('bcacdef')) //打印结果:acbcdef
  29. console.log(changeString('abcdef')) //打印结果:abcdef

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/769551
推荐阅读
相关标签
  

闽ICP备14008679号