simple solution in JAVA O(n)


  • 0

    '''

    public static String reverseWords(String s) {
    StringBuilder sb = new StringBuilder();

    char[] chArr = s.toCharArray();
    int head = 0;
    int tail = -1;
    
    for(char ch: chArr){
    	boolean isSpace = (int)ch == 32 ? true:false;
    	if(!isSpace){
    		tail++;
    	} else {
    		for(int i=tail; i>=head; i--){
    			sb.append(chArr[i]);
    		}
    		tail++;
    		head = tail+1;
    		sb.append(' ');
    	}
    }
    	
    for(int i=chArr.length-1; i>=head; i--)
    	sb.append(chArr[i]);
    
    return sb.toString();
    

    }


Log in to reply
 

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