151. Reverse Words in a String
Explanation:
To solve this problem, we can follow these steps:
- Trim the input string to remove leading and trailing spaces.
- Split the input string by spaces to extract individual words.
- Reverse the list of words.
- Join the reversed words with a single space to form the final result string.
Time complexity analysis:
- Splitting the string into words takes O(n) time, where n is the length of the input string.
- Reversing the list of words takes O(n) time.
- Joining the words back into a string takes O(n) time. Hence, the overall time complexity of this approach is O(n).
Space complexity analysis:
- The space complexity is O(n) where n is the length of the input string, as we are storing the split words in a list.
:
class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
StringBuilder result = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
result.append(words[i]);
if (i > 0) {
result.append(" ");
}
}
return result.toString();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.