Solution using Java string.split(String regex)


  • 0
    K
    public class Solution {
        public String reverseWords(String s) {
            String s1 = s.trim();
            //Since the argument to split() is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ")
            String[] ss = s1.split(" +");
            StringBuilder sb = new StringBuilder();
            for(int i = ss.length - 1; i >=0; i--){
                if(ss[i] != " "){
                    sb.append(ss[i]+" ");
                }
            }
            return sb.toString().trim();
        }
    }

Log in to reply
 

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