Reverse String

Problem:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".


Analysis:
Two pointers, swap left and right. 

Solution:

class Solution {
    public String reverseString(String s) {
        if (s == null || s.length() == 0)
            return s;
        int l = 0, r = s.length() - 1;
        char[] chars = s.toCharArray();
        while(l < r) {
            char temp = chars[l];
            chars[l] = chars[r];
            chars[r]  = temp;
            l++;
            r--;
        }
        return new String(chars);
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List