-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path151.reverse-words-in-a-string.java
63 lines (62 loc) · 1.3 KB
/
151.reverse-words-in-a-string.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* [151] Reverse Words in a String
*
* https://leetcode.com/problems/reverse-words-in-a-string/description/
*
* algorithms
* Medium (15.70%)
* Total Accepted: 182.8K
* Total Submissions: 1.2M
* Testcase Example: '""'
*
*
* Given an input string, reverse the string word by word.
*
*
*
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
*
*
*
* Update (2015-02-12):
* For C programmers: Try to solve it in-place in O(1) space.
*
*
* click to show clarification.
*
* Clarification:
*
*
*
* What constitutes a word?
* A sequence of non-space characters constitutes a word.
* Could the input string contain leading or trailing spaces?
* Yes. However, your reversed string should not contain leading or trailing
* spaces.
* How about multiple spaces between two words?
* Reduce them to a single space in the reversed string.
*
*
*
*/
public class Solution {
public String reverseWords(String s) {
int j = s.length();
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
j = i;
} else {
if (i == 0 || s.charAt(i - 1) == ' ') {
if (sb.length() != 0) {
sb.append(" ");
}
sb.append(s.substring(i, j));
}
}
}
return sb.toString();
}
}