Neat & modular 2ms Java solution with comments. Beats 97%.


  • 0
    P

    This solution is pretty long but its easy to understand and works flawlessly. I could have made it shorter but ended up doing this way. Not bad though.

    public void reverseWords(char[] s) { // Great solution. O(n) time and O(1) space.
    		if (s.length == 0)
    			return;
    		for (int i = 0; i < s.length;) {
    			int end = nextSpace(s, i);
    			if (end == -1)
    				break;
    			reverse(s, i, end); // reverse individual words.
    			i = end + 2;
    		}
    		reverse(s, 0, s.length - 1); // reverse complete set of chars.
    	}
    
    	private void reverse(char[] str, int start, int end) { // usual reverse function.
    		if (start >= end)
    			return;
    		for (int i = start; i <= (start + end )/ 2; i++) {
    			char temp = str[i];
    			str[i] = str[end - i + start];
    			str[end - i + start] = temp;
    		}
    	}
    
    	private int nextSpace(char[] str, int start) { // Find next character before space.
    		if (start >= str.length)
    			return -1;
    
    		for (int i = start; i < str.length; i++) {
    			if (str[i] == ' ') {
    				return i - 1;
    			}
    			if (i == str.length - 1)
    				return i;
    		}
    
    		return -1;
    	}
    
    

Log in to reply
 

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