Question
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 .
Notice
A word is defined as a character sequence consists of non-space characters only.
Example
Given s = "Hello World" , return 5 .
Review
Calcuate from the end to begin.
Solution
Java
public class Solution {
/**
* @param s A string
* @return the length of last word
*/
public int lengthOfLastWord(String s) {
// Write your code here
if (s == null) {
return 0;
}
int length = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char cter = s.charAt(i);
if (length == 0 && cter == ' ') {
continue;
}
if (length > 0 && cter == ' ') {
break;
}
++length;
}
return length;
}
}