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.
思路
从题意可以看出,从后往前看。找第一个某个不是空格的字符后面的空格,如果找到,说明已经过了一个word了。
Code
public class Solution { /** * @param s A string * @return the length of last word */ public int lengthOfLastWord(String s) { // Write your code here int count = 0; for (int i = s.length() - 1; i >= 0; i--) { char c = s.charAt(i); if (c == ' ') { if (count == 0) { continue; } else { break; } } else { count++; } } return count; } }