Reverse Twice


  • 1
    K
    1. Reverse the whole sentence
    2. Reverse each word
    public void reverseWords(char[] s) {
            int i=0;
            int j=s.length-1;
            // swap full sentence
            while(i<j) {
                swap(s, i, j);
                i++;
                j--;
            }
            i=0;j=0;
            int k=0;
            // swap word by word
            while(j<s.length) {
            	while(j<s.length && s[j] != ' ') {
            		j++;
            	}
            	k=j-1;
                    // swap the current word
            	while(i<k) {
            		swap(s,i,k);
            		i++;
            		k--;
            	}
            	j++;
            	i=j;
            }
        }
        
        private static void swap(char[] s, int i, int j) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.