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
.
题意:给定一个字符串,判断最后一个不包括“ ”字符串的长度。
思路:首先如果字符串如果为空,则返回0,否则,从字符串的最后一个字符开始。查找第一个不为“ ”的索引,然后开始计数,直到找到下一个“ ”返回计数器的值。
代码:
public int lengthOfLastWord(String s) { int count = 0; if(s.length()<=0) return 0; int index = s.length() - 1 ; while(index>=0&&s.charAt(index)==‘ ‘) { index--; } while(index>=0) { if(s.charAt(index)!=‘ ‘) { count++; index--; if(index<0) return count; }else { return count; } } return 0; }
LeetCode(58):Length of Last Word
原文:http://www.cnblogs.com/Lewisr/p/5117833.html