题目:http://oj.leetcode.com/problems/length-of-last-word/
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World",
return 5.
给定字符串s,由大小写字母和空字符' '组成,返回最后一个单词的长度。
如果最后一个单词不存在,返回0。
注意:单词的定义是只包含非空格字符的序列。
例如,
给定 s = "Hello World",
返回5。
分析:
从后往前,注意去除末尾的空字符。
C++实现:
class Solution {
public:
int lengthOfLastWord(const char *s) {
string str(s);
int i = str.length() - 1;
while(i >= 0 && str[i] == ' ')
{
--i;
}
int length = 0;
while(i >= 0 && str[i] != ' ')
{
++length;
--i;
}
return length;
}
};
Java实现:
public class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while(i >= 0 && s.charAt(i) == ' ') {
--i;
}
int length = 0;
while(i >= 0 && s.charAt(i) != ' ') {
++length;
--i;
}
return length;
}
}
Python实现:
class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
i = len(s) - 1
while i >= 0 and s[i] == ' ':
i -= 1
length = 0
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length
感谢阅读,欢迎评论!
本文详细介绍了如何使用 C++、Java 和 Python 三种语言解决 LeetCode 上的题目,即获取给定字符串中最后一个单词的长度。通过从后往前遍历字符串,去除末尾的空格,并计算非空字符的数量,最终得到答案。
&spm=1001.2101.3001.5002&articleId=19840937&d=1&t=3&u=3603699a033b4fa692516ffb2985152e)
1116

被折叠的 条评论
为什么被折叠?



