原题
https://leetcode-cn.com/problems/length-of-last-word/

思路
倒叙遍历,判断空格和计数的关系
题解
package com.leetcode.code;
/**
* @ClassName Code58
* @Author ZK
* @Description
* @Date 2021/2/4 9:59
* @Version 1.0
**/
public class Code58 {
public static void main(String[] args) {
String str = "hello world";
int i = lengthOfLastWord(str);
System.out.println(i);
}
public static int lengthOfLastWord(String s) {
int len = s.length();
int count = 0;
int index = len-1;
for (index = len-1; index >= 0; index--) {
char curChar = s.charAt(index);
if (curChar == ' ') {
if (count == 0) {
continue;
} else {
break;
}
} else {
count++;
}
}
if (index == -1) {
count = 0;
}
return count;
}
}
这篇博客主要介绍了如何解决 LeetCode 上的一个经典问题——计算字符串中最后一个单词的长度。作者通过倒序遍历字符串并判断空格来实现这一功能,代码简洁明了,适合初学者理解。

被折叠的 条评论
为什么被折叠?



