Simple Java Solution without using reverse()


  • 0
    S

    public String reverseWords(String s) {
    StringBuffer sb = new StringBuffer();
    for(int i=0; i<s.length(); i++){
    if(s.charAt(i) == ' ' || i == s.length()-1){
    int j = i == s.length()-1 ? i+1 : i;
    while(--j >= 0 && s.charAt(j) != ' ')
    sb.append(s.charAt(j));
    if(i != s.length()-1)
    sb.append(' ');
    }
    }
    return sb.toString();
    }


Log in to reply
 

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