434字符串中的单词统计
由于题目指出单词之间只会通过空格隔开,因此就很容易判断,只要当前一个字符是空格而当前字符不是空格就可以统计加一。
时间复杂度O(N),空间复杂度O(1)
class Solution {
public:
int countSegments(string s) {
int count = 0;
for(int i = 0; i < s.length(); i++){
if((i == 0 || s[i - 1] == ' ') && s[i] != ' ') count ++;
}
return count;
}
};
58最后一个单词的长度
这题也是只有单词和空格组成,因此只要从字符串的末尾开始遍历,从遇到的第一个非空格字符开始到下一个空格,统计字母个数。
时间复杂度O(N), 空间复杂度O(1)
class Solution {
public:
int lengthOfLastWord(string s) {
int count = 0;
if(s.length() == 0) return 0;
int i = s.length() - 1;
while( i >= 0 && s[i] == ' ') i--; //去掉末尾的空格
for( ; i >= 0; i--){
if(s[i] != ' ') count ++;
else break;
}
return count;
}
};