LeetCode 557: Reverse Words in a String III
Problem Description
Explanation:
To solve this problem, we can follow these steps:
- Split the given string by spaces to get individual words.
- Reverse each word separately.
- Join the reversed words back together with spaces in between.
Time complexity: O(n) where n is the length of the input string
Space complexity: O(n)
:
Solutions
class Solution {
public String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(new StringBuilder(word).reverse()).append(" ");
}
return result.toString().trim();
}
}
Related LeetCode Problems
Loading editor...