Description:
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
解题思路:
题目要我们给出字符串中最后一个字的长度,主要需要考虑到空格的问题。
从头开始遍历,若检测到这个字符不是空格且上一个字符是空格,则令计数器重置为1,即新的word开始遍历;
若检测到这个字符不是空格且上一个字符也不是空格,就是还在遍历这个word中,令word计数器+1。
代码:
class Solution { public: int lengthOfLastWord(string s) { int count = 0; for (int i = 0; i < s.size(); i++) { if (s[i] != ' ') { if (s[i-1] == ' ') { count = 1; } else { count++; } } } return count; } };