LeetCode

Leetcode151. Reverse Words in a

2017-02-25  本文已影响13人  Persistence2

Description:

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 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();
    }
}
上一篇下一篇

猜你喜欢

热点阅读