File tree Expand file tree Collapse file tree 1 file changed +27
-20
lines changed Expand file tree Collapse file tree 1 file changed +27
-20
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public String reverseWords (String s ) {
3
- int idx = 0 ;
4
- int n = s .length ();
5
- StringBuilder sb = new StringBuilder ();
6
- int start = 0 ;
7
- while (idx < n ) {
8
- while (idx < n && s .charAt (idx ) != ' ' ) {
9
- idx ++;
10
- }
11
- int curr = idx - 1 ;
12
- while (curr >= start ) {
13
- sb .append (s .charAt (curr --));
14
- }
15
- if (idx != n ) {
16
- sb .append (" " );
17
- }
18
- idx ++;
19
- start = idx ;
2
+ public String reverseWords (String s ) {
3
+ int start = 0 ;
4
+ int end = 0 ;
5
+ char [] chars = s .toCharArray ();
6
+ while (end < s .length ()) {
7
+ if (chars [end ] == ' ' ) {
8
+ if (start < end - 1 ) {
9
+ reverse (chars , start , end - 1 );
10
+ }
11
+ end ++;
12
+ start = end ;
13
+ } else {
14
+ end ++;
15
+ }
16
+ }
17
+ if (start < end ) {
18
+ reverse (chars , start , end - 1 );
19
+ }
20
+ return String .valueOf (chars );
21
+ }
22
+
23
+ private void reverse (char [] chars , int start , int end ) {
24
+ while (start < end ) {
25
+ char temp = chars [start ];
26
+ chars [start ++] = chars [end ];
27
+ chars [end --] = temp ;
28
+ }
20
29
}
21
- return sb .toString ();
22
- }
23
30
}
You can’t perform that action at this time.
0 commit comments