151. Reverse Words in a String

来源:互联网 发布:网店美工培训课程 编辑:程序博客网 时间:2024/06/14 20: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.

public class Solution {    public String reverseWords(String s) {        if (s == null || s.length() == 0) {            return "";        }        String[] array = s.split(" ");        StringBuilder sb = new StringBuilder();        for (int i = array.length - 1; i >= 0; --i) {            if (!array[i].equals("")) {                sb.append(array[i]).append(" ");            }        }        return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);    }}
原创粉丝点击