翻转字符串中的单词
https://leetcode.cn/problems/reverse-words-in-a-string/description/
思路
1、首先需要去除多余的空格
'the sky is blue'
1 2 3 4 5 6 7 8 9
| 1.1 先去除字符串首和重复出现的空格 if (strArr[fastIndex] === ' ' && (fastIndex===0 || strArr[fastIndex-1] === ' '))
1.2 去除字符串尾的空格
strArr.length = strArr[slowIndex-1] === ' '? slowIndex-1 : slowIndex
|
2、将整个字符串进行翻转
eg:'the sky is blue' --> 'eulb si yks eht'
1 2 3 4 5 6
| 使用双指针 while(left<right){ [strArr[left],strArr[right]] = [strArr[right],strArr[left]] left++ right++ }
|
3、然后找到每一个单词,对该单词进行翻转
eg:'eulb si yks eht' --> 'blue is the sky'
求解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| var reverseWords = function (s) { let strArr = Array.from(s) const removeBlank = (strArr) => { let slowIndex = 0 let fastIndex = 0 while (fastIndex < strArr.length) { if ( strArr[fastIndex] == ' ' && (fastIndex == 0 || strArr[fastIndex - 1] == ' ') ) { fastIndex++ } else { strArr[slowIndex] = strArr[fastIndex] slowIndex++ fastIndex++ } } strArr.length = strArr[slowIndex - 1] === ' ' ? slowIndex - 1 : slowIndex } const reverse_all = (arr, start, end) => { let left = start let right = end while (left < right) { ;[arr[left], arr[right]] = [arr[right], arr[left]] left++ right-- } } removeBlank(strArr) reverse_all(strArr, 0, strArr.length - 1) let startIndex = 0 for (let i = 0; i < strArr.length; i++) { if (strArr[i + 1] == ' ') { reverse_all(strArr, startIndex, i) startIndex = i + 2 } } reverse_all(strArr, startIndex, strArr.length - 1) return strArr.join('') }
|
右旋转字符串
https://kamacoder.com/problempage.php?pid=1065
思路
同上一道题思路相似,先全部反转,然后再把两部分各进行一次反转。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| var right_circle_string = (s,k)=>{ let strArr = Array.from(s) function reverse_word(sArr,start,end){ let left = start,right = end while(left<right){ [sArr[left], sArr[right]] = [sArr[right], sArr[left]] left++ right-- } return sArr } strArr = reverse_word(strArr,0,strArr.length-1) strArr = reverse_word(strArr,0,k-1) strArr = reverse_word(strArr,k,strArr.length-1) return strArr }
|