Accepted Java solution: Hash table implementation.


  • 0
    P

    Hi. This is an implementation using java.util.Hashtable and StringBuffer.
    Any comments or improvements are welcome.
    Cheers.

    import java.util.Hashtable;
    
    public class Solution {
        public String reverseWords(String inputString) {
    		
    		inputString = inputString.trim();
    		String[] words = inputString.split(" ");
    
    		int numberOfWords = words.length;
    		
    		Hashtable<Integer,String> H = new Hashtable<Integer,String>();
    		int pivot = numberOfWords -1;
    		int key = 0;
    
            // Add non-empty words in inverse order to Hashtable H from String[] words.
    		while(pivot>=0 && key < numberOfWords) {
    			if(!words[pivot].isEmpty()) {
    				H.put(key, words[pivot]);
    				key++; pivot--;
    			}
    			else {
    				pivot--;
    			}
    		}
    		
    		// Append elements of Hashtable H to StringBuffer buffer, separated with a space.
    		StringBuffer buffer = new StringBuffer();
    		for (int i=0; i< H.size(); i++) {
    			buffer.append(H.get(i));
    			buffer.append(" ");
    		}
    		return buffer.toString().trim();
    	}
    }

  • 3
    X

    It seems there is no need to add a Hashtable into your program. Why not use the array "words" directly to construct the new string?

    for (int i = words.length() - 1; i >= 0 ; i--) {
        if(!words[i].isEmpty()){
            buffer.append(words[i] + " ");
        }
    }

  • 0
    P

    Good observation.


  • 2
    J

    change

     inputString.split(" ");
    

    to

     inputString.split("\\s+")

  • 0
    J

    before return buffer.toString() remember to call trim()
    otherwise it wont pass the tests


Log in to reply
 

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