Easy Java solution


  • 0
    U
    public class Solution {
    public String reverseWords(String s) {
        String res="";
        String afterTrim= s.trim();
        String[] split=afterTrim.split(" +");
        StringBuilder sb= new StringBuilder();
        for(int i=split.length-1;i>=0;i--){
             sb.append(split[i]+" ");
        }
        return sb.toString().trim();
        
    }
    

    }


  • 0
    S

    Hi ,
    very intuitive answer
    I have a question that inplace of line String[] split=afterTrim.split(" +");
    if I put String[] split=afterTrim.split(" "); what is the difference.Please explain me.Also if the put the second line and execute as below it is failing for some test case.could you please explain why this happens?

    public class Solution {
    public String reverseWords(String s) {
        String res="";
        String afterTrim= s.trim();
        String[] split=afterTrim.split(" ");
        StringBuilder sb= new StringBuilder();
        for(int i=split.length-1;i>=0;i--){
             sb.append(split[i]+" ");
        }
        return sb.toString().trim();
    
    }
    
    }
    

  • 0
    U

    Hi, you can look up some common regular expression. " " means once meet a space, u do split, " +"means once meat a space go to see if there is any following space, if there is, include the consecutive space as a whole part, then split.
    you can write a small program to verify my answer.


Log in to reply
 

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