データ構造アルゴリズム/文字列は単語の反転によって空間複雑度O(1)を要求します.

1196 ワード

/**
 *      ,              ,           
 *                
 */
public class StringWordReverse {
    public String wordReverse(String str){
        //      string       ,        
        String temp = new StringBuffer(str).reverse().toString()+" ";
        int start = 0;
        int end = 0;
        char[] charArr = temp.toCharArray();
        for (int i = 0; i < charArr.length; i++) {
            if (charArr[i] != ' '){
                end = i;
            }else {
                for (int j = 0; j < (end-start+1)/2; j++) {//     
                    swap(start+j, end-j, charArr);
                }
                start = end + 2;//       
                end = end + 2;
            }
        }
        return new String(charArr);
    }

    public void swap(int i, int j, char[] charArr){
        char temp = charArr[i];
        charArr[i] = charArr[j];
        charArr[j] = temp;
    }

    public static void main(String[] args) {
        StringWordReverse stringWordReverse = new StringWordReverse();
        String result = stringWordReverse.wordReverse("q wfde wef");
        System.out.println(result);
    }
}