344. Reverse String

Question

Write a function that takes a string as input and returns the string reversed.

Example 1:

Input: "hello"
Output: "olleh"

Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

Example 1:

Input: "hello"
Output: "olleh"

Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

Thinking:

  • Method 1: StringBuilder
class Solution {
    public String reverseString(String s) {
        StringBuilder sb = new StringBuilder(s);
        return sb.reverse().toString();
    }
}
  • Method 2: 双指针
class Solution {
    public String reverseString(String s) {
        char[] arr = s.toCharArray();
        int low = 0, high = arr.length - 1;
        while(low < high){
            swap(arr, low++, high--);
        }
        return new String(arr);
    }
    private void swap(char[] arr, int i, int j){
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}