meta data for this page
  •  

Reverse Words in a String

Leetcode


Given an input string s, return a string of the words in reverse order concatenated by a single space.

Input: s = "the      sky    is  blue"
Output: "blue is sky the"

Solution:

Solution:

public static String reverseWords(String s) {
  s = s.trim();
  String[] words = s.split("\\s+");
  reverseWords(words);
  return String.join(" ", words);
}
public static void reverseWords(String[] words) {
  int l=0, r = words.length - 1;
  while (l < r) {
    String tmp = words[l];
    words[l++] = words[r];
    words[r--] = tmp;
  }
}