*LeetCode-Reverse Words in a String II

首先把整个string reverse 然后每个词再reverse

或者先每个词reverse 再整个reverse 注意最后一个词要记得reverse 这也是只有一个词的coner case的情况

public class Solution {
    public void reverseWords(char[] s) {
        reverse( s, 0, s.length - 1);
        int start = 0;
        int end = 0;
        for ( int i = 0; i < s.length; i ++ ){
            if ( s[ i ] == ' '){
                reverse ( s, start, end );
                start = i + 1;
            }
            else 
                end = i;
        }
        reverse ( s, start, end );
    }
    public void reverse ( char[] s, int start, int end ){
        while ( start < end ){
            char c = s[ start ];
            s[ start ] = s [ end ];
            s[ end ] = c;
            start ++;
            end --;
        }
    }
}


你可能感兴趣的:(*LeetCode-Reverse Words in a String II)