您的位置:首页 > 其它

LeetCode 151 Reverse Words in a String

2015-12-02 10:23 417 查看

题目描述

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

For example,

Given s = “the sky is blue”,

return “blue is sky the”.

Clarification:

[code]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.


分析

常规的做法是:

将字符串首尾的空格(leading or trailing spaces)去掉

翻转每个单词

翻转整个字符串

例如字符串:“the sky”

翻转前:

[code]the sky


翻转每个单词:

[code]eht yks


翻转整个字符串:

[code]sky the


利用Java的API,解这个题目只需要3行代码。

参考自:Reverse Words in a String

代码

[code]    public static String reverseWords(String s) {

        List<String> words = Arrays.asList(s.trim().split(" +"));

        Collections.reverse(words);

        return String.join(" ", words);
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: