-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWordsInStringIII.java
More file actions
29 lines (25 loc) · 998 Bytes
/
ReverseWordsInStringIII.java
File metadata and controls
29 lines (25 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package solutions;
// [Problem] https://leetcode.com/problems/reverse-words-in-a-string-iii
class ReverseWordsInStringIII {
// O(n) time, O(n) space
public String reverseWords(String s) {
StringBuilder output = new StringBuilder();
String[] words = s.split(" ");
for (String word: words) {
char[] lettersInWord = word.toCharArray();
for (int i = lettersInWord.length - 1; i >= 0; i--) {
output.append(lettersInWord[i]);
}
output.append(" ");
}
return output.toString().trim();
}
// test
public static void main(String[] args) {
ReverseWordsInStringIII solution = new ReverseWordsInStringIII();
String input = "Let's take LeetCode contest";
String expectedOutput = "s'teL ekat edoCteeL tsetnoc";
String actualOutput = solution.reverseWords(input);
System.out.println("Test passed? " + expectedOutput.equals(actualOutput));
}
}