Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
24 lines (21 loc) · 1013 Bytes

File metadata and controls

24 lines (21 loc) · 1013 Bytes
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* LC#58. Length of Last Word 最后一个单词的长度
* link :https://leetcode-cn.com/problems/length-of-last-word/
* 思路1:使用 split 分割空格字符串,获得字符数组 a[],再直接获取 a[] 最后一个元素的长度即可: a[a.length - 1].length()
* 思路2:先移除 s 尾部的空格,然后从尾部开始遍历递减字符串元素,当遇到 char == '' 时结束统计,变量 i 累积的值就是最后一个单词的长度,效率比解法1更加高效,无法切开字符处理
*/
public class S58 {
public int lengthOfLastWord(String s) {
int end = s.length() - 1;
while(end >= 0 && s.charAt(end) == ' ') end--;
if(end < 0) return 0;
int start = end;
while(start >= 0 && s.charAt(start) != ' ') start--;
return end - start;
}
public static void main(String[] args) {
String s = "Hello World";
int length = new S58().lengthOfLastWord(s);
System.out.println(length);
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.