码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Words in a String

时间:2015-01-13 13:54:37      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

https://oj.leetcode.com/problems/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".

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

解题思路:

首先trim s,去除开始就有的首尾空格,然后用空格将其split为数组。再倒序,最后trim首尾的空格。

其他思路的解法较多:

例如先倒置整个s,然后从头开始倒置每个单词(遇到空格),再处理头尾的空格和中间的空格。

也可以使用stack的方法,推进去,再取出来。

Reverse Words in a String

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4220920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!