最后一个单词长度
说明
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。
示例 2:
输入:s = " fly me to the moon "
输出:4
解释:最后一个单词是“moon”,长度为4。
示例 3:
输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为6的“joyboy”。
提示:
1 <= s.length <= 104s仅有英文字母和空格' '组成s中至少存在一个单词
来源:力扣(LeetCode) 链接:leetcode.cn/problems/le…
题解
解法一(调用API)
最简单的方式就是调用API,然后获取到最后一个元素的长度
public static void main(String[] args) {
String s = "Hello World";
System.out.println(demo(s));
}
public static int demo(String s){
String[] s1 = s.split(" ");
return s1[s1.length - 1].length();
}
解法二
public static void main(String[] args) {
String s = "Hello World";
System.out.println(demo(s));
}
public static int demo(String s){
//去掉空格
s = s.trim();
for (int i = s.length() - 1; i > -1 ; i--) {
if(' ' == s.charAt(i)){
return s.length() - i - 1;
}
}
return s.length();
}
\