题目描述:
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.
例子:
Input: "Hello World" Output: 5
分析:
题意:给定一个字符串s,只包含大小写字母表和空格。返回最后一个单词字符串的长度。
思路:我们对字符串进行逆序遍历,显然需要找到最后一个单词之前的空格。假设字符串总长度为n,我们用flag表示是否出现字母,则分为4种情况讨论:① s[i] == ' '、flag == false,说明还没有遇到字母,跳过;② s[i] == ' '、flag == true,说明找到了最后的单词、且遇到了空格,结束搜索,跳出;③ s[i] != ' '、flag == false,说明遇到了最后单词的第一个字母,但是搜索还没结束,答案加一,且flag置为true;④ s[i] != ' '、flag == true,说明遇到了最后单词中间的字母,但是搜索还没结束,答案加一。
最后返回答案。时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
int n = s.length();
// Exceptional Case:
if(n == 0){
return 0;
}
bool flag = false;
int ans = 0;
for(int i = n - 1; i >= 0; i--){
if(s[i] == ' ' && !flag){
continue;
}
else if(s[i] == ' ' && flag){
break;
}
else if(s[i] != ' ' && !flag){
flag = true;
ans++;
}
else if(s[i] != ' ' && flag){
ans++;
}
}
return ans;
}
};