557. Reverse Words in a String III
Reverse Words in a String III
Given a string s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "God Ding" Output: "doG gniD"
Constraints:
1 <= s.length <= 5 * 104
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.- There is at least one word in
s
. - All the words in
s
are separated by a single space.
- Break string into words
- Reverse each word
- Join reach word again
/**
* @param {string} s
* @return {string}
*/
const reverse = function(s){
if(!s || s.length <2) return s;
return s.split('').reverse().join('');
}
var reverseWords = function(s) {
return s.split(" ").map((w) => {
return reverse(w);
}).join(" ");
};
Time Complexity
We are breaking the string by space to fetch words(m) and let's say each word has n length, hence the time complexity will be O(n*m).
Space Complexity
We are not using any extra space here
That’s all folks! In this post, we solved LeetCode problem #557. Reverse Words in a String III using Build Methods.
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to solve leetcode questions & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment