DEV Community

YuehBen66
YuehBen66

Posted on

LeetCode 344. Reverse String

題目連結:LeetCode 344

 

一開始沒有多想,想說在迴圈裡儲存字串,
然後把字串中第 i 個字母跟倒數第 i 個字母值對調就做出來了~

/**
 * @Time Complexity : O(n)
 * @Space Complexity : O(n)
 */

var reverseString = function(s) {
   for (let i = 0; i < s.length / 2; i++) {
      let temp = s[i];
      s[i] = s[s.length - i - 1];
      s[s.length - i - 1] = temp;
   }
   return s;
}
Enter fullscreen mode Exit fullscreen mode

 

後續看見題目的 Follow up 寫說需要達成 O(1) 的空間複雜度,
因此想到了迴圈裡的每個 temp 並不需要被儲存,只是一個過渡而已,
所以可以把他拉到迴圈外

/**
 * @Time Complexity : O(n)
 * @Space Complexity : O(1)
 */

var reverseString = function(s) {
   let temp;
   for (let i = 0; i < s.length / 2; i++) {
      temp = s[i];
      s[i] = s[s.length - i - 1];
      s[s.length - i - 1] = temp;
   }
   return s;
}
Enter fullscreen mode Exit fullscreen mode

 

就可以完成 Follow up 的需求了

Top comments (0)