Reverse Words in a String

Posted YuriFLAG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Reverse Words in a String相关的知识,希望对你有一定的参考价值。

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.

思路:采用String 的 split 方法进行分割 , 其分割的正则表达式为" ".

 1 public class Solution {
 2     /**
 3      * @param s : A string
 4      * @return : A string
 5      */
 6     public String reverseWords(String s) {
 7         if(s == null || s.length() == 0) {
 8             return "";
 9         }
10         String[] words = s.split(" ");
11         StringBuilder builder = new StringBuilder();
12         for (int i = words.length - 1; i >= 0; i--) {
13             if (words[i] != " ") {
14                 builder.append(words[i]).append(" ");
15             }
16         }
17         return builder.length() == 0 ? "":builder.substring(0, builder.length() - 1);
18     }
19 }

 

以上是关于Reverse Words in a String的主要内容,如果未能解决你的问题,请参考以下文章

186. Reverse Words in a String II

LeetCode Reverse Words in a String III

4.Reverse Words in a String III

Reverse Words in a String leetcode

leetcode557. Reverse Words in a String III

Reverse Words in a String--not finished yet