Leetcode - reverse string under specific requirement

輸入一個string,把里面每個單詞翻轉,例如"this is a test", 輸出"tset a si siht"
并且題目保證了string里只有小寫字母和空格,并且有k個單詞的話一定只有k - 1個空格

My code:

public String reverse(String s) {
        if (s == null || s.length() == 0)
                return s;
        StringBuilder sb = new StringBuilder();
        int begin = s.length() - 1;
        int end = s.length() - 1;
        while (end >= 0) {
            if (begin == end) {
                if (s.charAt(begin) == ' ') {
                    begin--;
                    end--;
                }
                else {
                    sb.append(s.charAt(end));
                    end--;
                }
            }
            else if (s.charAt(end) != ' ') {
                sb.append(s.charAt(end));
                end--;
            }
            else if (s.charAt(end) == ' ') {
                sb.append(" ");
                end--;
                begin = end;
            }
        }
        if (end < begin) {
            return sb.toString();
        }
        else {
            return sb.substring(0, sb.length() - 1);
        }
    }

沒什么好說的。reverse string. 然后用 stringbuilder 倒序把他們收集起來。注意空格。

Anyway, Good luck, Richardo!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容