-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReverseWordsInString.java
More file actions
51 lines (42 loc) · 1.43 KB
/
Copy pathReverseWordsInString.java
File metadata and controls
51 lines (42 loc) · 1.43 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Given an input string, reverse the string word by word.
// See: https://leetcode.com/problems/reverse-words-in-a-string/
package leetcode.string;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ReverseWordsInString {
/**
* Solution 2. StringBuilder will increase the performance but it is not a
* challenge.
*/
public String reverseWords(String s) {
String ans = "";
String currWord = "";
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++) {
char ch = arr[i];
if (ch != ' ') {
currWord += ch;
} else if (!currWord.isEmpty()) {
ans = currWord + " " + ans;
currWord = "";
}
}
ans = currWord + " " + ans;
return ans.trim();
}
/**
* Solution 1: Easy solution with Java Arrays/Collections API
*/
public String reverseWords_var1(String s) {
List<String> list = Arrays.asList(s.trim().split("\\s+"));
System.out.println(list);
Collections.reverse(list);
return String.join(" ", list.toArray(new String[list.size()]));
}
public static void main(String[] args) {
ReverseWordsInString sln = new ReverseWordsInString();
System.out.println(sln.reverseWords("the sky is blue"));
System.out.println(sln.reverseWords(" hello world"));;
}
}