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".

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.

文字列の中の単語の逆順序出力を話して、単語の中のアルファベットの順序は変化しません.ここで、文字列の先頭のスペースは削除する必要があります.文字列に余分なスペースがある場合は、1つのスペースを出力するだけです.
考え方1:正規表現
正規表現の詳細については、私のブログを参照してください.ここでは、文の単語をsplitの正規表現で読み取るだけです.ここで用いられる正規表現は\s+であり、すなわち、1つまたは複数の空白に遭遇したときにブレークする.
    public String reverseWords(String s) {
        String[] array = s.trim().split("\\s+");
        String result = "";
        for(int i = array.length-1 ; i>0 ; i--){
            result += array[i] + " ";
        }
        return result + array[0];
    }

考え方2:ダブルポインタ
実はダブルポインタはここでもStringのAPIを使っていますが、核心的な考え方はやはりダブルポインタで単語の位置を見つけ、サブ文字列を得る方法で抽出して結果セットに加えることです.
    public String reverseWords(String s){
        String trimmed = s.trim();
        int prev = trimmed.length();
        int index = prev;
        StringBuilder result = new StringBuilder();
        while ((index = trimmed.lastIndexOf(' ', index-1)) > 0) {
            if (index < prev-1) {
                result.append(trimmed.substring(index+1, prev));
                result.append(" ");
            }
            prev = index;
        }
        result.append(trimmed.substring(index+1, prev));
        return result.toString();
    }

より多くの開発技術、面接チュートリアル、インターネット会社のプッシュを知りたいなら、私の微信の公衆番号に注目してください.不定期で福祉が支給されますよ~