Middle-题目126:151. Reverse Words in a String

原创 2016年05月31日 20:21:46

题目原文:
Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.
题目大意:
输入一个字符串,把空格分隔的字符串翻转。
题目分析:
先修剪(trim)掉两边的空格,然后按空格分隔,逆序输出即可。
源码:(language:java)

public class Solution {
    public String reverseWords(String s) {
        s=s.trim();
        String[] words = s.split(" ");
        String result = "";
        for(int i = words.length-1;i>0;i--) {
            if(!words[i].equals(""))
                result=result+words[i]+" ";
        }
        if(words.length!=0)
            result+=words[0];
        return result;
    }
}

成绩:
58ms,beats 8.93%,众数3ms,13.42%
Cmershen的碎碎念:
本题成绩较差,因为用到了两个String的库函数。其实这道题非常非常的水,问题出现在很多奇怪的边界情况,如首尾的空格,还有只有一个单词的情况……
用python是不是可以一两行搞定。。。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode151—Reverse Words in a String

LeetCode151—Reverse Words in A String

151. Reverse Words in a String

Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", r...

LeetCode 151. Reverse Words in a String

题目: Given an input string, reverse the string word by word. For example, Given s = "the sky is bl...

leetcode 151. Reverse Words in a String

Given an input string, reverse the string word by word. For example, Given s = "the sky is blue"...

Leetcode 151 Reverse Words in a String

给出一个字符串,将其中的字符串按单词顺序翻转.给出 s = "the sky is blue",返回 "blue is sky the".

<LeetCode OJ> 151. Reverse Words in a String

151. Reverse Words in a String My Submissions Question Total Accepted: 93077 Total Submissions: ...

[Leetcode] 151. Reverse Words in a String 解题报告

题目: Given an input string, reverse the string word by word. For example, Given s = "the sky...

[leetcode] 151. Reverse Words in a String 解题报告

题目链接:https://leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reverse the s...

算法Week02.02 - LeetCode 151. Reverse Words in a String

LeetCode 151. Reverse Words in a String

[LeetCode]problem 151. Reverse Words in a String

TAG字符串反转块反转题目链接方法题目要求O(1)空间,不知怎么,立即想到了《编程之美》上“将一个数循环移位k位”的题目。如此可以满足时间为O(n),且空间复杂度为O(1).具体步骤 将字符串中每个单...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)