Reverse String

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"

Analysis

反转字符串,用two pointers很直观。

Solution

Two Pointers

public class Solution {
    public String reverseString(String s) {
        char[] chs = s.toCharArray();
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            char temp = chs[i];
            chs[i] = chs[j];
            chs[j] = temp;
            i++;
            j--;
        }
        return new String(chs);
    }
}

Reference

Six Solutions (Java) - https://leetcode.com/problems/reverse-string/discuss/80937/JAVA-Simple-and-Clean-with-Explanations-6-Solutions

Last updated