3
#yyds干货盘点# leetcode算法题:最后一个单词的长度
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.
#yyds干货盘点# leetcode算法题:最后一个单词的长度
原创给你一个字符串 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;
}
}
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;
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK