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.
Example:
Input: "Hello World"
Output: 5
这道题很考对各种情况的分析以及对corner case的考虑!!!很能锻炼思维是否严谨,以及对推导过程的考察。
class Solution {
public int lengthOfLastWord(String s) {
//speical case
if (s.length() == 0) return 0;
//base case
if (s.length() == 1) return s.equals(" ") ? 0 : 1;
int count = 0;
//general case
for (int i = s.length() - 1; i > 0; i--) {
if (s.charAt(i) != ' ') {
if (s.charAt(i - 1) == ' ') {
return ++count;
} else {
count++;
}
//corner case: "a " !!!
} else {
if (s.charAt(i - 1) != ' ' && i == 1) {
return ++count;
}
}
}
//corner case: "aaa" , " " !!!
return count == 0 ? 0 : ++count;
}
}