给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = "Hello World"
输出:5
示例 2:
输入:s = " fly me to the moon "
输出:4
示例 3:
输入:s = "luffy is still joyboy"
输出:6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/length-of-last-word
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
package com.wei.happydemo;
public class Solution {
public static int lengthOfLastWord(String s){
int index = s.length() - 1;
while (s.charAt(index) == ' '){
index--;
}
int wordLength = 0;
while(index >= 0 && s.charAt(index) != ' '){
wordLength++;
index--;
}
return wordLength;
}
public static void main(String[] args) {
String str="ad dff dfga q ";
int i = lengthOfLastWord(str);
System.out.println(i);
}
}
class Solution {
public int lengthOfLastWord(String s) {
//首先要清楚的是最后一个是空格还是字母
//如果不是字母 就从后往前进行判断 直到遇见字母停下
int index = s.length() - 1;
while(s.charAt(index) == ' '){
index--;
}
//到这里就是遇到了字母
//然后进行判断,如果是遇到了下一个空格且索引大于等于0 就说明要么是最后一个字母,要么是只有一个字母
int wordLength = 0;
while(index >= 0 && s.charAt(index) != ' '){
wordLength++;
index--;
}
return wordLength;
}
}