File tree Expand file tree Collapse file tree 2 files changed +10
-43
lines changed Expand file tree Collapse file tree 2 files changed +10
-43
lines changed Original file line number Diff line number Diff line change 1
1
public class ReverseWordsInAString {
2
2
3
3
public static String reverseWords (String s ) {
4
- s = s .trim ();
5
- if (s .length () == 0 ) {
6
- return "" ;
7
- }
8
- StringBuilder sb = new StringBuilder ();
4
+ int i , j = 0 ;
9
5
boolean flag = false ;
10
- int i = s .length () - 1 , j = i ;
11
- for (i = s .length () - 1 , j = i ; i >= 0 ; i --) {
6
+
7
+ StringBuilder sb = new StringBuilder ();
8
+
9
+ for (i = s .length () - 1 ; i >= 0 ; i --) {
12
10
if (s .charAt (i ) == ' ' ) {
13
11
if (!flag ) {
14
12
continue ;
15
13
} else {
16
- sb .append (s .substring (i + 1 , j + 1 )).append (" " );
17
14
flag = false ;
15
+ sb .append (s .substring (i + 1 , j + 1 )).append (" " );
18
16
}
19
17
} else {
20
18
if (!flag ) {
21
- j = i ;
22
19
flag = true ;
20
+ j = i ;
23
21
}
24
22
}
25
23
}
26
- if (j > i ) {
24
+
25
+ if (flag ) {
27
26
sb .append (s .substring (i + 1 , j + 1 ));
28
27
}
29
- if (sb .charAt (sb .length () - 1 ) == ' ' ) {
28
+ if (sb .length () > 0 && sb . charAt (sb .length () - 1 ) == ' ' ) {
30
29
sb .setLength (sb .length () - 1 );
31
30
}
32
31
return sb .toString ();
Original file line number Diff line number Diff line change 2
2
3
3
public class Main {
4
4
5
- public static String reverseWords (String s ) {
6
- int i , j = 0 ;
7
- boolean flag = false ;
8
-
9
- StringBuilder sb = new StringBuilder ();
10
-
11
- for (i = s .length () - 1 ; i >= 0 ; i --) {
12
- if (s .charAt (i ) == ' ' ) {
13
- if (!flag ) {
14
- continue ;
15
- } else {
16
- flag = false ;
17
- sb .append (s .substring (i + 1 , j + 1 )).append (" " );
18
- }
19
- } else {
20
- if (!flag ) {
21
- flag = true ;
22
- j = i ;
23
- }
24
- }
25
- }
26
-
27
- if (flag ) {
28
- sb .append (s .substring (i + 1 , j + 1 ));
29
- }
30
- if (sb .length () > 0 && sb .charAt (sb .length () - 1 ) == ' ' ) {
31
- sb .setLength (sb .length () - 1 );
32
- }
33
- return sb .toString ();
34
- }
35
-
36
5
public static void main (String [] args ) {
37
- System .out .println (reverseWords ("the sky is blue" ));
38
6
}
39
7
}
You can’t perform that action at this time.
0 commit comments