Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.
Example:
Input: "Hello World" Output: 5
题目难度:简单题
解法一:从前往后扫描。
1 int lengthOfLastWord(string s) { 2 int cnt = 0; 3 int curr = 0; //用于记录当前字符串的长度 4 for (int i = 0; i < s.length(); ++i) { 5 if (s[i] == ' ') { 6 if (curr != 0) { 7 cnt = curr; 8 } 9 curr = 0; 10 } else { 11 ++curr; 12 } 13 } 14 if ((s.length() > 0) && (s[s.length() - 1] != ' ')) { //如果最后一个字符不是空格,那么替换成最后字符串的长度 15 cnt = curr; 16 } 17 return cnt; 18 }
解法二:从后往前扫描
1 int lengthOfLastWord(string s) { 2 int cnt = 0; 3 int index = s.length() - 1; 4 while (index >= 0 && (s[index] == ' ')) index--; 5 while (index >= 0 && s[index] != ' ') { 6 --index; 7 cnt++; 8 } 9 return cnt; 10 }