首页 > 其他 > 详细

Reverse Words in a String

时间:2015-01-13 13:53:03      阅读:113      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!