Java Solution using two pointers


  • 0
    K
    public class Solution {
        public void reverseWords(char[] s) {
            reverse(s, 0, s.length - 1);
            for (int i = 0, j = 0; i < s.length; i++) {
                if (s[i] == ' ') {
                    reverse(s, j, i - 1);
                    j = i + 1;
                } else if (i == s.length - 1) {
                    reverse(s, j, i);
                }
            }
        }
        
        public void reverse(char[] s, int start, int end) {
            for (int i = start, j = end; i < j; i++, 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.