Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
39 lines (29 loc) · 870 Bytes

151.md

File metadata and controls

39 lines (29 loc) · 870 Bytes

151. Reverse Words in a String

Description

Given an input string, reverse the string word by word.

For example, Given s = "the sky is blue", return "blue is sky the".

Thinking Process

  1. Get rid of leading and trailing spaces
  2. Get rid of extra spaces in between
  3. Split by space, and recreate the sentence using StringBuilder

Code

public class Solution {
    public String reverseWords(String s) {
        String s1 = s.trim();
        String s2 = s1.replaceAll("\\s+", " ");

        String[] words = s2.split(" ");
        StringBuilder sb = new StringBuilder();
        
        for(int i = words.length - 1; i >= 0; i--){
            sb.append(words[i]);
            sb.append(" ");
        }
        if(sb.length() == 0)
            return "";
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}