1. 程式人生 > >LeetCode——917. 僅僅反轉字母(JavaScript)

LeetCode——917. 僅僅反轉字母(JavaScript)

給定一個字串 S,返回 “反轉後的” 字串,其中不是字母的字元都保留在原地,而所有字母的位置發生反轉。

示例 1:

輸入:"ab-cd"
輸出:"dc-ba"

示例 2:

輸入:"a-bC-dEf-ghIj"
輸出:"j-Ih-gfE-dCba"

示例 3:

輸入:"Test1ng-Leet=code-Q!"
輸出:"Qedo1ct-eeLg=ntse-T!"

提示:

1.  S.length <= 100
2.  33 <= S[i].ASCIIcode <= 122 
3.  S 中不包含 \ or "

思路

第一步先將非字母字元固定,第二步開始排字母,搞定。
其中,大寫字母的ASCII碼:65 ~ 90,小寫字母:97 ~ 122

使用陣列來儲存排列後的順序:

let arr = Array(S.length)	// 長度為S.length的空陣列,每個元素都是undefined

第一步,將非字母字元固定。

  for (let i = 0; i < S.length; i++) {
    let ascii = S[i].charCodeAt()
    if ((ascii < 65) || (ascii > 90 && ascii < 97)) { // 不是字母的字元先放好
      arr[i] = S[i]
    }
  }

第二步,排列字母

let
j = S.length - 1 for (let i = 0; i < S.length; i++) { let ascii = S[i].charCodeAt() while (arr[j] !== undefined) { j-- } if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <=122)) { arr[j] = S[i] } }

完整程式碼

/**
 * @param {string} S
 * @return {string}
 */
var reverseOnlyLetters = function(S) { let arr = Array(S.length) for (let i = 0; i < S.length; i++) { let ascii = S[i].charCodeAt() if ((ascii < 65) || (ascii > 90 && ascii < 97)) { // 不是字母的字元先放好 arr[i] = S[i] } } let j = S.length - 1 for (let i = 0; i < S.length; i++) { let ascii = S[i].charCodeAt() while (arr[j] !== undefined) { j-- } if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <=122)) { arr[j] = S[i] } } return arr.join('') };