题目描述:
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。单词是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例:
输入:s = " fly me to the moon " 输出:4
解题方法:这道题相对简单,首先去掉字符串 s 末尾的空格,声明一个临时变量 result 来记录单词的长度,然后从后往前遍历 s,如果不是空格,则 result ++,遇到空格,直接 return 即可。题目中已经说明 s 仅由字母和空格组成,所以不需要去考虑非字母的情况。
public class LengthOfLastWord {
public static int lengthOfLastWord(String s) {
if (s == null) {
return 0;
}
s = s.trim();
int result = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c != ' ' ) {
result += 1;
} else {
return result;
}
}
return result;
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
String str = " I Love China ";
int result = lengthOfLastWord(str);
System.out.println("result = " + result);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
}
}