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.
For example,
Given s = "Hello World"
,
return 5
.
方法1:正序遍历整个字符串,碰到非空格字符‘ ’ ,len++,碰到空格字符且后一个字符为非空格字符,则len清零
class Solution{
public:
int lengthOfLastWord(string s) {
int n = s.length();
int i = 0;
int len = 0;
if ((n == 1) && (s[0] != ' ')) return 1;
while (s[i]){
if (s[i] != ' ') //碰到非空格字符,len++
len++;
else if (s[i + 1] && s[i] == ' '&&s[i + 1] != ' ') //碰到空格字符且后一个字符为非空格字符,len清零
len = 0;
i++;
}
return len;
}
};
方法二:反序遍历,从字符串末尾开始遍历,碰到非空格字符就开始len++,当碰到非空格字符,且前一个字符为空格字符时,立即结束,返回len
class Solution{
public:
int lengthOfLastWord(string s) {
int n = s.length();
int j = n-1;
int len = 0;
while (j>=0){
if (s[j] != ' ') //碰到非空格字符,len++
len++;
if (s[j] != ' '&&s[j - 1] == ' ') //碰到非空格字符,且前一个字符是空格字符,则立即返回len,结束
return len;
j--;
}
return len;
}
};
#include<iostream>
#include<string>
using namespace std;
class Solution{
public:
int lengthOfLastWord(string s) {
int n = s.length();
int j = n-1;
int len = 0;
while (j>=0){
if (s[j] != ' ') //碰到非空格字符,len++
len++;
if (s[j] != ' '&&s[j - 1] == ' ') //碰到非空格字符,且前一个字符是空格字符,则立即返回len,结束
return len;
j--;
}
return len;
}
};
int main()
{
string s = "hello world";
Solution sol;
int t = sol.lengthOfLastWord(s);
cout << t << endl;
system("pause");
return 0;
}