题目: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
感谢阅读,欢迎评论!