Reverse Words in a String

题目地址:
https://leetcode.com/problems/reverse-words-in-a-string/#/description

题目:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
解题思路:
这道题就是双指针用

代码:

public String reverseWords(String s) {
    if(s == null || s.length() <= 1){
        return s;
    }

    char[] chars = s.toCharArray();
    helper(chars, 0, chars.length - 1);

    int size = chars.length;
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < size; i++){
        sb.append(chars[i]);
    }

    return sb.toString();
}

private void helper(char[] chars, int start, int end){
    if(start == end || start - 1 == end){
        return;
    }
    helper(chars, start + 1, end - 1);

    char temp = chars[start];
    chars[start] = chars[end];
    chars[end] = temp;

}



Comments

Popular Posts