meta data for this page
Reverse Words in a String
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"
jump to: Search / User Tools / Main Content / Change Content Width
Software Quality Engineering & Beyond
You are here: SQE & Beyond » Interview Questions » Algorithm Interview Questions » Reverse Words in a String
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"
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; } }