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. Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
To solve this problem, we need to:
function reverseWordsBruteForce(s: string): string { // Split the string by spaces and filter out empty strings let words = s.trim().split(/\s /); // Reverse the array of words words.reverse(); // Join the words with a single space return words.join(' '); }
This solution is efficient given the constraints. However, it uses additional space for the array of words.
If the string data type is mutable and we need to solve it in-place with O(1) extra space, we can use a two-pointer technique to reverse the words within the original string.
function reverseWordsOptimized(s: string): string { // Trim the string and convert it to an array of characters let chars = s.trim().split(''); // Helper function to reverse a portion of the array in place function reverse(arr: string[], left: number, right: number) { while (leftTime Complexity Analysis:
console.log(reverseWordsBruteForce("the sky is blue")); // "blue is sky the" console.log(reverseWordsBruteForce(" hello world ")); // "world hello" console.log(reverseWordsBruteForce("a good example")); // "example good a" console.log(reverseWordsBruteForce("singleWord")); // "singleWord" console.log(reverseWordsBruteForce(" ")); // "" console.log(reverseWordsOptimized("the sky is blue")); // "blue is sky the" console.log(reverseWordsOptimized(" hello world ")); // "world hello" console.log(reverseWordsOptimized("a good example")); // "example good a" console.log(reverseWordsOptimized("singleWord")); // "singleWord" console.log(reverseWordsOptimized(" ")); // ""
String Manipulation:
Two-Pointer Technique:
In-Place Algorithms:
By practicing such problems and strategies, you can improve your problem-solving skills and be better prepared for various coding challenges.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3