The input string contains spaces, and we use the space as the boundary to divide the string. split ("")
Then we traverse the split strings and stitch them together.
Finally, let's make a judgment. If the last character is a space, it should be deleted. Note here that we must first determine whether the string after splicing is an empty string
public static String reverseWords(String s) { if(s.length()==0) return s; String [] words = s.split(" "); StringBuilder ans = new StringBuilder(); for(int i=words.length-1;i>0;i--){ if(words[i].length()==0) continue; ans.append(words[i]); ans.append(" "); } if(ans.charAt(ans.length())==' '){ ans.deleteCharAt(ans.length()); } return ans.toString(); }