LeetCode/com/zerroi/leetcode/Three11/LengthOfLastWord.java

37 lines
1.2 KiB
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}