1. 程式人生 > >leetcode 151. Reverse Words in a String 字串 翻轉

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”,
return “blue is sky the”.

思路:按照空格分割後存到字串數組裡,然後從後向前遍歷儲存,需要注意前面的空格和後面的空格。
注意區分“”和“ ”的區別。

package test;

public class str {
    public static String reverseWords(String s) {
        if (s == null
) { return ""; } String[] array = s.split(" "); StringBuilder res = new StringBuilder(); for (int i = array.length - 1; i >= 0; i--) { if (!"".equals(array[i])) { res.append(array[i]); res.append(" "); } } return
res.length() == 0 ? "" : res.substring(0, res.length() - 1) .toString(); } public static void main(String[] args) { System.out.print(reverseWords(" f ttt t ")); } }