[Java] Same trick with [Reverse Words in a String] I & II


  • 0
    M

    Notice that when you do the nested while loops, add the outer condition also into inner condition so that you won't out of boundary accidently.

    public class Solution {
        public String reverseWords(String s) {
            char[] array = s.toCharArray();
            int start = 0;
            int index = 0;
            while (index < array.length) {
                while (index < array.length && array[index] != ' ') index++;
                reverse(array, start, index - 1);
                index++;
                start = index;
            }
            StringBuilder sb = new StringBuilder();
            for (char ch : array) {
                sb.append(ch);
            }
            return sb.toString();
        }
        private void reverse(char[] array, int start, int end) {
            while (start < end) {
                char tmp = array[start];
                array[start] = array[end];
                array[end] = tmp;
                start++;
                end--;
            }
        }
    }
    

Log in to reply
 

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