-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_rev.java
More file actions
34 lines (29 loc) · 991 Bytes
/
Solution_rev.java
File metadata and controls
34 lines (29 loc) · 991 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
30
31
32
33
34
class Solution_rev {
public String reverseWords(String s) {
int start = 0;
int end = s.length();
StringBuilder sbb = new StringBuilder();
while (start < end) {
// Skip leading spaces
while (start < end && s.charAt(start) == ' ') {
start++;
}
// Find the end of the current word
int j = start;
while (j < end && s.charAt(j) != ' ') {
j++;
}
// Extract the word if it exists
if (start < j) {
String word = s.substring(start, j);
if (sbb.length() > 0) {
sbb.insert(0, " "); // Prepend a space before the next word
}
sbb.insert(0, word); // Prepend the word itself
}
// Move start to the next word
start = j + 1;
}
return sbb.toString(); // Return the reversed words
}
}