My accepted solution with Java


  • 1
    I
    public class Solution {
    public String reverseWords(String s) {       
    	s=s.trim();     
        int n=s.length();
        String str="";
        while(s.lastIndexOf(" ")!=-1){      	
            int index=s.lastIndexOf(" ");
            str=str+s.substring(index+1,n)+" ";
            s=s.substring(0,index).trim();
            n=s.length();
        }
        if(n>0)
        	str=str+s.substring(0,n);
        return str;
    }
    

    }


  • 2
    S

    Very clever, no data structures needed.

    Unlike mine :

    public class Solution {
    public String reverseWords(String s) {
        StringBuilder sep = new StringBuilder();
        s = s.trim();
        int length = s.length();
        String[] strings = s.trim().split(" ");
        Stack<String> stringList = new Stack<String>();
        for (String str : strings) {
            if (!str.equals("")) {
               stringList.add(str);
               stringList.add(" ");
        }
      }
      while(stringList.size()>0){
          sep.append(stringList.pop());
      }
      return sep.toString().trim();
    }
    

    }


  • 0
    Z
    	String[] words = s.trim().split(" +");
    
    	StringBuffer buffer = new StringBuffer();
    	for(int i = words.length - 1;i >= 0; --i){
    		if(i == 0){
    			buffer.append(words[i].trim());
    		}else{
    			buffer.append(words[i].trim());
    			buffer.append(" ");	
    		}
    	}
    	return buffer.toString();
    

Log in to reply
 

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