344. Reverse String
一、題目
Write a function that reverses a string. The input string is given as an array of characters s
.
You must do this by modifying the input array in-place with O(1)
extra memory.
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"]
Constraints:
1 <= s.length <= 105
s[i]
is a printable ascii character.
二、程式作法
public class Solution
{
public void ReverseString(char[] s)
{
//System.Array.Reverse(s);
int left = 0;
int right = s.Length - 1;
while (left < right)
{
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
三、思路筆記
題目要的結果為將一陣列的排列做反轉,兩種作法,
第一種作法,我們知道第一個元素會與倒數第一個做交換,第二個元素會與倒數第二個做交換,
所以也是宣告左右兩指標來逼近中間,進而完成反轉需求。
第二種作法,直接呼叫 System.Array.Reverse() 方法來幫我們處理到好。