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",
return5.
思路:从后向前扫描,定位lastword然后记录其长度。
public class Solution {
public int lengthOfLastWord(String s) {
if (s == null || s.length() < 1)
return 0;
int n = s.length();
int i;
int len = 0;
boolean in = false;
for (i = n - 1; i >= 0; i--) {
if (!in && s.charAt(i) != ' ') {
in = true;
}
if (in && s.charAt(i) != ' ') {
len++;
}
if (in && s.charAt(i) == ' ')
break;
}
return len;
}
public static void main(String[] args) {
System.out.println(new Solution().lengthOfLastWord("Hello World"));
System.out.println(new Solution().lengthOfLastWord("Hello World "));
System.out.println(new Solution().lengthOfLastWord("Hello a "));
System.out.println(new Solution().lengthOfLastWord(""));
System.out.println(new Solution().lengthOfLastWord(" "));
}
}
来源:oschina
链接:https://my.oschina.net/u/1584603/blog/284507