LeetCode:Reverse Words in a String

原创 2016年05月31日 11:38:32

Reverse Words in a String




Total Accepted: 102953 Total Submissions: 655369 Difficulty: Medium

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

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Subscribe to see which companies asked this question

Hide Tags
 String
Hide Similar Problems
 (M) Reverse Words in a String II






















思路:

s中两边可能有空格,单词之间可能有多个空格,这些都需要去掉。

用正则表达式就是爽~~~


java code:

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


版权声明:本文为博主原创文章,转载请注明出处。

相关文章推荐

Reverse words in a string-leetcode

  • 2014年08月30日 18:27
  • 197B
  • 下载

【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】

【152-Reverse Words in a String(反转字符串中的单词)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given an input strin...

将一个英文句子单词顺序逆置(LeetCode | Reverse Words in a String)

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

[LeetCode186]Reverse Words in a String II

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space...

[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", ret...

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”, ...
  • fly_yr
  • fly_yr
  • 2015年11月01日 15:07
  • 613

《leetCode》: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之186_Reverse Words in a String 字符串词序反转算法

给定一个字符串S,反转其中存在的单词顺序,将

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

https://leetcode.com/problems/reverse-words-in-a-string/tabs/description Given an input s...

LeetCode OJ 之 Reverse Words in a String (翻转字符串的单词)

题目: Given an input string, reverse the string word by word.(给定一个输入字符串,按单词翻转这个字符串) For exampl...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode:Reverse Words in a String
举报原因:
原因补充:

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