原題
https://leetcode-cn.com/problems/length-of-last-word/
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxCNBRUT5NXblhGZzwEMW1mY1RzRapnTtxkb5ckYplTeMZTTINGMShUYfRHelRHLwEzX39GZhh2css2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3Pn5GcugTM4MjMwADM2AjMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
思路
倒叙周遊,判斷空格和計數的關系
題解
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;
}
}