Simple Java Solution, charArray


  • 0
    F
    public class Solution {
        public String reverseWords(String s) {
            char[] words = s.toCharArray();
            
            for (int i = 0, j = 0; j <= words.length; j++) {
                if (j == words.length || words[j] == ' ') {
                    reverse(words, i, j - 1);
                    i = ++j;
                }
            }
            
            return String.valueOf(words);
        }
        
        private void reverse(char[] words, int i, int j) {
            while (i < j) {
                char tmp = words[j];
                words[j--] = words[i];
                words[i++] = tmp;
            }
        }
    }
    

Log in to reply
 

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