Java solution using regex


  • 4
    A
    public class Solution {
        public String reverseWords(String s) {
            s = s.trim();
            String[] words = s.split(" +");
            StringBuilder str = new StringBuilder();
            
            if (words.length != 0) {
                for (int i = words.length - 1; i > 0; i--) {
                    str.append(words[i] + " ");
                }
                str.append(words[0]);
            }
            
            return str.toString();
            
        }
    }

  • 0
    X

    Very great use of regex. First time finding regex is a wonderful thing personally.

    s = s.trim();
    
    String words[] = s.split(" +"); // regex
    if (words.length == 0) // debug for leetcode
    	return s;
    
    StringBuilder sb = new StringBuilder();
    for (int i = words.length - 1; i >= 0; i--)
    	sb.append(words[i] + " ");
    return sb.deleteCharAt(sb.length() - 1).toString();
    

Log in to reply
 

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