151. Reverse Words in a String

来源:互联网 发布:毕向东java全套视频 编辑:程序博客网 时间:2024/06/08 04:55
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) {        String[] array = s.split(" ");        StringBuilder res = new StringBuilder();        for(int i=array.length-1; i>=0; i--) {            if(array[i].isEmpty()) continue;            res.append(array[i]);            res.append(" ");        }        if (res.length() == 0) return res.toString();        else return res.toString().substring(0, res.length()-1);    }

对应的  

186. Reverse Words in a String II 增加了一个限制

Could you do it in-place without allocating extra space?

要求不额外开辟空间 感觉不是很好想 类似 

48. Rotate Image http://blog.csdn.net/daimingyang123/article/details/78747262
这种reverse或者rotate 并要求in-place的 多想想两步完成 

public void reverseWords(char[] s) {    // Three step to reverse    // 1, reverse the whole sentence    reverse(s, 0, s.length - 1);    // 2, reverse each word    int start = 0;    int end = -1;    for (int i = 0; i < s.length; i++) {        if (s[i] == ' ') {            reverse(s, start, i - 1);            start = i + 1;        }    }    // 3, reverse the last word, if there is only one word this will solve the corner case    reverse(s, start, s.length - 1);}public void reverse(char[] s, int start, int end) {    while (start < end) {        char temp = s[start];        s[start] = s[end];        s[end] = temp;        start++;        end--;    }}