[LeetCode] 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.
反转字符串。
题目既是题意。思路很简单,two pointer 两边往中间逼近做法。
时间O(n)
空间O(1) - 这也是题目要求
Java实现
1 class Solution { 2 public void reverseString(char[] s) { 3 int i = 0; 4 int j = s.length - 1; 5 while (i < j) { 6 char temp = s[i]; 7 s[i] = s[j]; 8 s[j] = temp; 9 i++; 10 j--; 11 } 12 } 13 }
JavaScript实现
1 /** 2 * @param {character[]} s 3 * @return {void} Do not return anything, modify s in-place instead. 4 */ 5 var reverseString = function(s) { 6 let left = 0; 7 let right = s.length - 1; 8 while (left < right) { 9 let temp = s[left]; 10 s[left] = s[right]; 11 s[right] = temp; 12 left++; 13 right--; 14 } 15 };
相关题目