Reverse Words in a String, Leetcode 解题笔记

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

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

click to show 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.

一开始想复杂了,还想到用stack去了,其实就是把string split成数组形式,然后倒序合并就行了,这里利用StringBuilder比较方便。

public class Solution {
    public String reverseWords(String s) {
        if(s == null || s.length() == 0) return "";
        String[] arr = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for(int i = arr.length-1; i >= 0; i--){
                sb.append(arr[i]).append(" "); 
        if(sb.length() == 0) return "";
        else return sb.substring(0, sb.length()-1);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s