File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ ``` java
2
+ package sy181129 ;
3
+
4
+ import java.util.Stack ;
5
+
6
+ /**
7
+ * @author suyuan
8
+ *
9
+ *给定一个字符串,逐个翻转字符串中的每个单词。
10
+
11
+ 示例:
12
+
13
+ 输入: "the sky is blue",
14
+ 输出: "blue is sky the".
15
+ 说明:
16
+
17
+ 无空格字符构成一个单词。
18
+ 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
19
+ 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
20
+ */
21
+ public class leetcode_151 反转字符串里的单词
22
+ {
23
+
24
+ public static void main (String [] args )
25
+ {
26
+ String string= " the sky is blue" ;
27
+ System . out. println(reverseWords(string));
28
+
29
+ }
30
+
31
+ public static String reverseWords (String s ) {
32
+ String str= s. trim();
33
+ if (str. equals(" " ))
34
+ return " " ;
35
+ if (str. equals(" " ))
36
+ return " " ;
37
+ Stack<String > stack= new Stack<> ();
38
+ StringBuilder sb= new StringBuilder ();
39
+ String [] split = str. split(" \\ s+" );
40
+ for (String str1: split)
41
+ {
42
+ stack. push(str1);
43
+ }
44
+ int size= stack. size();
45
+ for (int i= 0 ;i< size;i++ )
46
+ {
47
+ sb. append(stack. pop()+ " " );
48
+ }
49
+ sb. deleteCharAt(sb. length()- 1 );
50
+ return sb. toString();
51
+ }
52
+ }
53
+ ```
You can’t perform that action at this time.
0 commit comments