Share my java solution and implement String.split()


  • 0
    C
    public String reverseWords(String s) {
        StringBuilder ret = new StringBuilder();
        String[] words = split(s); 
        //or split by system method
        //words = s.split("\\s+");
        for (int i = words.length - 1; i >= 0; i--){
        	ret.append(words[i]);
        	if(i != 0) ret.append(" ");
        }
        return ret.toString();
    }
    private String[] split(String s){
    	int lastChar = 1; // 1 : space, 0 : non-space
    	int len = 0;
    	char[] charArray = s.toCharArray();
    	for (char c : charArray) {
    		if(c == ' ') lastChar = 1;
    		else{
    			len += lastChar;
    			lastChar = 0;
    		}
    	}
    	String[] words = new String[len];
    	StringBuilder word = new StringBuilder();
    	int index = 0;
    	lastChar = 1;
    	for (char c : charArray) {
    		if(c == ' '){
    			if(lastChar == 0) words[index++] = word.toString();
    			lastChar = 1;
    		}
    		else{
    			if(lastChar == 1){
    				word.setLength(0);
    			}
    			word.append(c);
    			lastChar = 0;
    		}
    	}
    	if(lastChar == 0) words[index] = word.toString();
    	return words;
    }

Log in to reply
 

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