觀前提醒:
Write a function that reverses a string. The input string is given as an array of characters char[]
.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
認真講解,在不呼叫內建函式的前提下,他的正統解法,就是利用two pointers + memorization
來處理。我們把核心函式,一步步來用圖片整理如下:
(抱歉我這圖,是用onenote 內建畫筆畫的,有點醜QQ)
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function (s) {
let i = 0;
let j = s.length - 1;
let temp = "";
while (i < j) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
};
我相信一定不少朋友跟我一樣,在對於 JS 略懂略懂的前提下,看到這題 input 是 array,加上要反轉他
。便開始反射動作要用 "Array.reverse()"
這個內建函式,來結束這一會合。
但,基本上LeetCode Easy 的題目,基本上就是希望大家用"條件判斷 + 迴圈"
等基本概念來解題。所以內建函式我們這邊就不寫了,因為那真的太簡短,反而會讓大家學不到東西XDDD
謝謝大家的收看,LeetCode 小學堂我們下次見~