151. Reverse Words in a String

Description

Given an input string, reverse the string word by word.
For example,Given s = "the sky is blue
",return "blue is sky the
".
**Update (2015-02-12):
**For C programmers: Try to solve it in-place in O(1) space.
click to show clarification.
Clarification:
What constitutes a word?A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?Reduce them to a single space in the reversed string.

Solution

Two pointers

思路還是很清晰的,先翻轉(zhuǎn)每個(gè)word,再翻轉(zhuǎn)整個(gè)String。
有坑的地方是:

  1. 開頭和結(jié)尾的space要移除掉。
  2. word之間要保留一個(gè)space。這個(gè)可以邊遍歷邊對(duì)words進(jìn)行計(jì)數(shù),遇到新單詞且之前已經(jīng)有單詞才插入space。
public class Solution {
    public static void main(String[] args) {
        final String input = "  ab c dec   ";
        System.out.println("[" + new Solution().reverseWords(input) + "]");
    }

    public String reverseWords(String s) {
        if (s == null || s.isEmpty()) {
            return s;
        }
        char[] chars = s.toCharArray();
        int len = compressWords(chars);
        reverseStr(chars, 0, len - 1);
        return String.valueOf(chars, 0, len);
    }

    public int compressWords(char[] chars) {
        int i = 0;
        int j = 0;
        int wordsCount = 0;

        while (i < chars.length) {
            // escape spaces and find the beginning of a new word
            while (i < chars.length && chars[i] == ' ') {
                ++i;
            }
            if (i == chars.length) break;
            if (wordsCount > 0) {
                chars[j++] = ' ';   // leave a space in between of words
            }
            int k = j;
            // find the ending of the word
            while (i < chars.length && chars[i] != ' ') {
                chars[j++] = chars[i++];
            }
            reverseStr(chars, k, j - 1);
            ++wordsCount;
        }

        return (j > 0 && chars[j - 1] == ' ') ? j - 1 : j; // remove the trailing space if any
    }

    public void reverseStr(char[] chars, int start, int end) {
        while (start < end) {
            char tmp = chars[start];
            chars[start++] = chars[end];
            chars[end--] = tmp;
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容