Thursday, June 2, 2016

Leetcode: 344. Reverse String

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


Code (Java):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public String reverseString(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
         
        char[] cs = s.toCharArray();
        int start = 0;
        int end = s.length() - 1;
         
        while (start < end) {
            swap(cs, start, end);
            start++;
            end--;
        }
         
        return new String(cs);
    }
     
    private void swap(char[] cs, int i, int j) {
        char temp = cs[i];
        cs[i] = cs[j];
        cs[j] = temp;
    }
}

No comments:

Post a Comment