一、题目描述
二、代码实现
2.1 字符串分割split()
将一个字符串用“ ”分割成多个字符串并存放在字符串数组中,然后求数组中最后一个字符串的长度即可。
package com.it.leetcode;
public class Day_0003 {
public static void main(String[] args) {
System.out.println(lengthOfLastWord("hello world")); //5
System.out.println(lengthOfLastWord("hello world6")); //6
System.out.println(lengthOfLastWord("hello world77")); //7
System.out.println(lengthOfLastWord("hello world888")); //8
System.out.println(lengthOfLastWord(" j")); //1
System.out.println(lengthOfLastWord(" fly me to the moon ")); //4
}
private static int lengthOfLastWord(String s) {
String[] strArray = s.split(" ");
String strNew = strArray[strArray.length - 1];
return strNew.length();
}
}
2.2 反向遍历字符串
package com.it.leetcode;
public class Day_0003 {
public static void main(String[] args) {
System.out.println(lengthOfLastWord1("hello world")); //5
System.out.println(lengthOfLastWord1("hello world6")); //6
System.out.println(lengthOfLastWord1("hello world77")); //7
System.out.println(lengthOfLastWord1("hello world888")); //8
System.out.println(lengthOfLastWord1(" j")); //1
System.out.println(lengthOfLastWord1(" fly me to the moon ")); //4
}
//反向遍历字符串
private static int lengthOfLastWord1(String s) {
int count = 0;//记录最后一个单词的个数
int index = s.length() - 1;
//先去除最后面的空格
while (s.charAt(index) == ' ' && index >= 0) {
index--;
}
//正式计算最后一个单词的长度。注意index >=0的条件一定要放在前面,避免出现访问下标为-1的情况
while (index >= 0 && s.charAt(index) != ' ') {
count ++;
index --;
}
return count;
}
}