3

#yyds干货盘点# leetcode算法题:最后一个单词的长度

 2 years ago
source link: https://blog.51cto.com/u_13321676/5488218
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# leetcode算法题:最后一个单词的长度

原创

灰太狼_cxh 2022-07-20 10:00:42 博主文章分类:leetcode ©著作权

文章标签 字符串 子字符串 代码实现 文章分类 Java 编程语言 阅读数195

给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。

单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。

输入:s = "Hello World"

解释:最后一个单词是“World”,长度为5。

输入:s = "   fly me   to   the moon  "

解释:最后一个单词是“moon”,长度为4。

输入:s = "luffy is still joyboy"

解释:最后一个单词是长度为6的“joyboy”。

代码实现:

class Solution {
public 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;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK