My Java in-place Solution


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

Log in to reply
 

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