[LeetCode]-[JavaScript]-[解題]-Reverse String-反轉字串

文、意如

題目精簡說明:

在同一個陣列中 s ,把元素從最後元素顯示到最前元素

 

 

原始題目:

Write a function that reverses a string. The input string is given as an array of characters s.

範例參考:

Example 1:

Input: s = ["h","e","l","l","o"]

Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]

Output: ["h","a","n","n","a","H"]


解題思路:

1.把元素從最後面讀出

2.讀到元素後馬上寫回原陣列

3.最後再把原來的陣列資料刪除

4.只留下自己寫入的元素

參考程式碼:

/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function(s) {
   a=[]
   lens=s.length
   for(i=lens-1;i>=0;i--){
       s.push(s[i])
   }
   s.splice(0,lens)
};

 

執行結果:

 

 

 

 

Yiru@Studio - 關於我 - 意如