Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Your output should have a single space between each word and no extra spaces. \n\n* Constraints:\n * 1 <= s.length <= 10^4\n * s contains English letters (lower-case and upper-case), digits, and spaces.\n * There is at least one word in s.\n* Examples:\n \n Input: s = "the sky is blue"\n Output: "blue is sky the"\n \n \n Input: s = " hello world "\n Output: "world hello"\n \n \n Input: s = "a good example"\n Output: "example good a"\n

Solution

Approach:\n1. Split Words: First, we need to extract the individual words from the input string. The split() method (or equivalent in other languages), when called without arguments, handles multiple spaces and leading/trailing spaces correctly, splitting by any whitespace and discarding empty strings.\n2. Reverse Order: Once we have a list of words, reverse the order of this list.\n3. Join Words: Finally, join the reversed list of words back into a single string, using a single space character as the separator between words.\n\nPython Code:\npython\nclass Solution:\n def reverseWords(self, s: str) -> str:\n # Split the string by one or more spaces.\n # s.split() by default handles multiple spaces and trims leading/trailing.\n words = s.split()\n \n # Reverse the list of words in-place\n words.reverse()\n \n # Join the words with a single space\n return " ".join(words)\n\n\nAlternative (More Manual/In-Place Consideration):\nFor languages like C++/Java, or if an in-place solution is required (modifying the original character array without extra space proportional to input size), the approach often involves:\n1. Reverse the entire string.\n2. Reverse each word: Iterate through the reversed string, identify word boundaries (non-space characters), and then reverse each individual word.\n3. Clean up spaces: Handle multiple spaces and trim leading/trailing spaces during or after the process to ensure a single space between words.