reverse the string and then every words


  • 0
    2
    public class Solution {
        public void reverseWords(char[] s) {
            reverse(s, 0, s.length - 1);
            int lo = 0;
            for (int i = 0; i <= s.length; i++) {
                if (i == s.length || s[i] == ' ') {
                    reverse(s, lo, i - 1);
                    lo = i + 1;
                }
            }
        }
        private void reverse(char[] c, int lo, int hi) {
            while (lo < hi) {
                char temp = c[lo];
                c[lo] = c[hi];
                c[hi] = temp;
                lo++;
                hi--;
            }
        }
    }
    

Log in to reply
 

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