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.
求最后一个单词的长度。
思路:,利用string.Trim()去掉字符串最左和最右的空格,后从后往前遍历,从第一个字符开始到第一个空格结束。
public class Solution {
public int LengthOfLastWord(string s) {
s = s.Trim();
int lastIndex = s.LastIndexOf(' ') + 1;
return s.Length - lastIndex;
}
}