Java Solution without pre-defined split.


  • 0
    M
    public class Solution {
        public String reverseWords(String s) {
            if(s==null || s.trim().length()==0)
                return s;
            int i=0,j=0;
            char[] arr = s.toCharArray();
            while(i<arr.length && j<arr.length){
                while(j<arr.length && arr[j]!=' '){
                    j++;
                }
                reverse(arr, i, j-1);
                while(j<arr.length && arr[j]==' '){
                	j++;
                }
                i=j;
            }
            return new String(arr);
        }
        
        public void reverse(char[] arr, int start, int end){
            while(start<arr.length && end<arr.length && start<end && end>=0){
                    char c = arr[end];
                    arr[end] = arr[start];
                    arr[start] = c;
                    start++;
                    end--;
            }
        }
    }
    

Log in to reply
 

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