Introduction

1.Description(Easy)

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

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

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.

2.Code

用split函数将string分成一个一个单词,在从后往前一次append到stringbuilder中,注意最后检查下是否remove last space,但是test中不加这个检查也能pass。

public String reverseWords(String s){
        if(s==null || s.length()==0){
            return "";
        }
        StringBuilder result=new StringBuilder();
        String[] str=s.split(" ");
        for(int i=str.length-1;i>=0;i--){
            if(!str[i].equals("")){
                result.append(str[i]).append(" ");
            }
        }
        //remove the last " "
        if(result.length()==0){
            return "";
        }else{
            return result.toString();
        }

    }

Last updated