Simple Java Solution


  • 8
    P
    public class Solution {
        public String reverseWords(String s) {
            String [] words = s.split(" ");
            StringBuilder sb = new StringBuilder();
            int end = words.length - 1;
            for(int i = 0; i<= end; i++){
                if(!words[i].isEmpty()) {
                    sb.insert(0, words[i]);
                    if(i < end) sb.insert(0, " ");
                }
            }
            return sb.toString();
        }
    }

  • 0
    S

    Can someone please explain this solution?
    Thanks.


  • 2
    T

    @sagardafle split the string by space to an array of words, and keep adding those words in a same order to the front of the stringbuilder .
    for example, the array of the word is: ["the","sky","is","blue"]
    the stringbuilder will be: ["the"] ["sky","the"] ["is", "sky","the"] ["blue","is","sky","the"] every time adding the word


  • 0
    S

    @tonic.tao Thanks a lot :) That helped me.


Log in to reply
 

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