Leetcode 557. Reverse Words in a String III
Given a string s
, you need to 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 * 10^4
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.s
.s
are separated by a single space.s
mutable, or should we consider creating a new result string?
StringBuilder
.s
by spaces to get individual words.s.split(" ")
.String.join(" ", <list of reversed words>)
to combine the reversed words back into a single string.public class Solution {
public String reverseWords(String s) {
// Split the input string into words
String[] words = s.split(" ");
// Reverse each word
for (int i = 0; i < words.length; i++) {
words[i] = new StringBuilder(words[i]).reverse().toString();
}
// Join the reversed words with space
return String.join(" ", words);
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
System.out.println(solution.reverseWords("Let's take LeetCode contest")); // "s'teL ekat edoCteeL tsetnoc"
System.out.println(solution.reverseWords("God Ding")); // "doG gniD"
}
}
The time complexity of this solution is O(n), where n
is the length of the input string s
. This is because:
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?