37 lines
1.2 KiB
Java
37 lines
1.2 KiB
Java
|
package com.zerroi.leetcode.Three11;
|
|||
|
|
|||
|
public class LengthOfLastWord {
|
|||
|
public static void main(String[] args) {
|
|||
|
SolutionSecond solutionSecond = new SolutionSecond();
|
|||
|
// int res = solutionSecond.lengthOfLastWord(" fly me to the moon ");
|
|||
|
// int res = solutionSecond.lengthOfLastWord("Hello World");
|
|||
|
int i = solutionSecond.lengthOfLastWord("a ");
|
|||
|
System.out.println("i = " + i);
|
|||
|
// System.out.println("res = " + res);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
/*
|
|||
|
* 给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
|
|||
|
|
|||
|
单词 是指仅由字母组成、不包含任何空格字符的最大
|
|||
|
子字符串
|
|||
|
。*/
|
|||
|
class SolutionSecond {
|
|||
|
public int lengthOfLastWord(String s) {
|
|||
|
int res = 0;
|
|||
|
boolean flag = false;
|
|||
|
for (int i = s.length() - 1; i >= 0; i--) {
|
|||
|
// 从字符串后面开始遍历,找到第一字母出现的位置开始记录
|
|||
|
if (s.charAt(i) != ' ') {
|
|||
|
res++;
|
|||
|
flag = true;
|
|||
|
} else if (flag) {
|
|||
|
return res;
|
|||
|
}
|
|||
|
}
|
|||
|
// System.out.println(s.substring(startIndex, endIndex + 1));
|
|||
|
return res;
|
|||
|
}
|
|||
|
}
|