-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverseWordsInAString.java
36 lines (30 loc) · 1010 Bytes
/
ReverseWordsInAString.java
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
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// https://leetcode.com/problems/reverse-words-in-a-string/
public class ReverseWordsInAString {
private final String input;
public ReverseWordsInAString(String input) {
this.input = input;
}
public String solution() {
List<String> result = new ArrayList<>();
int pointer = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
String candidate = input.substring(pointer, i).trim();
if (candidate.length() != 0) {
result.add(candidate);
}
pointer = i;
}
}
String candidate = input.substring(pointer).trim();
if (candidate.length() != 0) {
result.add(candidate);
}
Collections.reverse(result);
return String.join(" ", result);
}
}