Simple Java AC solution using for loop


  • 0
    G
    public class Solution {
        public String reverseWords(String s) {
            if(s == null || s.length() == 0)
                return "";
            
            String[] values = s.split("\\ ");   //split the string based on " "(one space)
            String result = "";
            
            for(int j = values.length-1; j>=0; j--) //start from back side of the string
            {
                if(values[j].length() > 0)  //append only the string length is greater than 0
                {
                    result = result + values[j];
                    if(j!=0)
                        result += " ";
                }   
            }
            
            return result.trim();
        }
    }
    

Log in to reply
 

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