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 }

AC C++:

 1 class Solution {
 2 public:
 3     void reverseString(vector<char>& s) {
 4         int i = 0;
 5         int j = s.size() - 1;
 6         while(i < j){
 7             swap(s[i++], s[j--]);
 8         }
 9     }
10 };

跟上Reverse String IIReverse Vowels of a String.

posted @ 2016-08-27 05:44  Dylan_Java_NYC  阅读(261)  评论(0编辑  收藏  举报