题目描述:

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

解题思路:

这道题坑还是有的,一开始从后面找想找空格,返回空格后字符串的长度,没想到它直接给我个"a "。

然后我换了个思路找字母,每碰到一个字母就让length+1,同样还是用空格作为结束循环的条件,不过这次多加了一个条件blankFlag==0。blankFlag一开始设置为1,当遇到字母时变0。所以跳出循环的条件的意思就是:第二次碰到空格。最后返回length。

代码:

 1 class Solution {
 2 public:
 3     int lengthOfLastWord(string s) {
 4         int length=0;//最后一个单词长度
 5         bool blankFlag=1;
 6         for(int i=s.length()-1;i>=0;i--){
 7         //从字符串的末尾进行搜索
 8             if(s[i]!=' '){
 9             //碰到字母
10                 length++;
11                 blankFlag=0;
12             }
13             if(s[i]==' '&&blankFlag==0)
14             //跳出循环
15                 break;
16         }
17         return length;
18     }
19 };

 

posted on 2018-02-03 15:20  宵夜在哪  阅读(94)  评论(0编辑  收藏  举报