LeetCode 344. Reverse String

原题链接在这里:https://leetcode.com/problems/reverse-string/

题目:

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"]

题解:

Reverse string是常见题, string在Java中是primitive类型, 一旦生成不可改变.

But we have the array of char here. Then use two pointers. Remember to move pointer in while loop.

Time Complexity: O(s.length).

Space: O(1).

AC Java:

 1 class Solution {
 2     public void reverseString(char[] s) {
 3         int l = 0;
 4         int r = s.length - 1;
 5         
 6         while(l < r){
 7             char temp = s[l];
 8             s[l] = s[r];
 9             s[r] = temp;
10             
11             l++;
12             r--;
13         }
14     }
15 }

跟上Reverse String IIReverse Vowels of a String.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5812194.html