美文网首页LeetCode
Leetcode151. Reverse Words in a

Leetcode151. Reverse Words in a

作者: Persistence2 | 来源:发表于2017-02-25 17:04 被阅读13次

    Description:

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

    For example,

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

    思路:

    • 倒序找单词
    • 找到之后就append

    代码:

    public class Solution {
        public String reverseWords(String s) {
            if (s == null || s.length() == 0) {
                return s;
            }
            int len = s.length(),end = len;
            StringBuilder result = new StringBuilder();
            for (int i = len - 1; i >= 0; i--) {
                if (s.charAt(i) == ' ') {
                    end = i;
                } else if (i == 0 || s.charAt(i-1) == ' ') {
                    if (result.length() != 0) {
                        result.append(' ');
                    }
                    result.append(s.substring(i, end));
                }
            }
            return result.toString();
        }
    }
    

    相关文章

      网友评论

        本文标题:Leetcode151. Reverse Words in a

        本文链接:https://www.haomeiwen.com/subject/kohnwttx.html