A simple and fast Java solution


  • 0
    public class Solution {
        public void reverseWords(char[] s) {
            reverse(s, 0, s.length - 1);
            
            int i = 0, j = 0;
            while (j < s.length) {
                while (j < s.length && s[j] != ' ') j++;
                reverse(s, i, j - 1);
                i = ++j;
            }
        }
        
        private void reverse(char[] s, int i, int j) {
            while (i < j) {
                char tmp = s[i];
                s[i++] = s[j];
                s[j--] = tmp;
            }
        }
    }
    

Log in to reply
 

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