File tree Expand file tree Collapse file tree 2 files changed +82
-0
lines changed Expand file tree Collapse file tree 2 files changed +82
-0
lines changed Original file line number Diff line number Diff line change
1
+ 557 . 反转字符串中的单词 III
2
+
3
+ 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
4
+
5
+ 示例 1:
6
+
7
+ 输入: "Let's take LeetCode contest"
8
+ 输出: "s'teL ekat edoCteeL tsetnoc"
9
+ 注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
10
+
11
+ class Solution {
12
+
13
+ // https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/submissions/
14
+
15
+ // TODO 空复O(1) 未AC
16
+ // public String reverseWords(String s) {
17
+ // s = s.trim();
18
+ // if(s.length() < 2) return s;
19
+ // char[ ] wordChar = s.toCharArray();
20
+ // String result = "";
21
+ // for(int i=0; i<=wordChar.length; i++){
22
+ // if(i == wordChar.length || ' ' == wordChar[ i] ){
23
+ // for(int j=i-1; j>=0; j--){
24
+ // if(wordChar[ j] == ' ' && j != wordChar.length - 1) {
25
+ // result += " ";
26
+ // break;
27
+ // }
28
+ // if(j == 0) result += " ";
29
+ // // if(result.equals("") && wordChar[ j] == ' ') continue;
30
+ // // if(j == wordChar.length-1)
31
+ // result += wordChar[ j] ;
32
+ // }
33
+ // continue;
34
+ // }
35
+ // }
36
+ // return result;
37
+ // }
38
+
39
+
40
+ public String reverseWords(String s) {
41
+ String[ ] strs = s.split(" ");
42
+ StringBuilder sb = new StringBuilder();
43
+ for(String str: strs ){
44
+ char[ ] chars = str.toCharArray();
45
+ for(int i=0,j=chars.length-1;i<j;i++,j--){
46
+ char temp = chars[ i] ;
47
+ chars[ i] = chars[ j] ;
48
+ chars[ j] = temp;
49
+ }
50
+ sb.append(new String(chars) + " ");
51
+ }
52
+ return sb.toString().trim();
53
+ }
54
+
55
+ }
Original file line number Diff line number Diff line change
1
+
2
+ 58 . 最后一个单词的长度 https://leetcode-cn.com/problems/length-of-last-word/
3
+
4
+ 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
5
+
6
+ 如果不存在最后一个单词,请返回 0 。
7
+
8
+ 说明:一个单词是指由字母组成,但不包含任何空格的字符串。
9
+
10
+ 示例:
11
+
12
+ 输入: "Hello World"
13
+ 输出: 5
14
+
15
+
16
+ class Solution {
17
+ public int lengthOfLastWord(String s) {
18
+ s = s.trim();
19
+ int result = 0;
20
+ if("".equals(s)) return result;
21
+ if(!s.contains(" ")) return s.length();
22
+ for(int i = s.lastIndexOf(" ")+1; i<s.length(); i++){
23
+ result++;
24
+ }
25
+ return result;
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments