151. Reverse Words in a String

来源:互联网 发布:淘宝中差评处理 编辑:程序博客网 时间:2024/05/16 15:24

Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.

public class Solution {    public String reverseWords(String s) {    if (s == null) return null;    char[] a = s.toCharArray();    int n = s.length();    reverse(a, 0, n-1);    reverseWord(a, n);    return cleanspace(a, n);  }    public void reverse(char[] a, int start, int end) {        while (start < end) {            char tmp = a[start];            a[start++] = a[end];            a[end--] = tmp;        }    }    public void reverseWord(char[] a, int n) {        int i = 0, j = 0;        while (i < n) {            while (i < j || i < n && a[i] == ' ') i++;            while (j < i || j < n && a[j] != ' ') j++;            reverse(a, i, j-1);        }    }    public String cleanspace(char[] a, int n) {        int i = 0, j  = 0;        while (j < n) {            while (j < n && a[j] == ' ') j++;            while (j < n && a[j] != ' ') a[i++] = a[j++];            while (j < n && a[j] == ' ') j++;            if (j < n) a[i++] = ' ';        }        return new String(a).substring(0, i);    }}
0 0
原创粉丝点击