您的位置:首页 > 其它

54:Length of Last Word

2017-02-28 22:20 330 查看
题目: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 consist

解题代码一(从后往前扫描):

// 逆序扫描
// 时间复杂度 O(n),空间复杂度 O(1)
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0;

int i = s.size() - 1;
while (i >= 0)
if (s[i] == ' ') --i;
else break;

while (i >= 0)
if (s[i] != ' ') ++len, --i;
else break;
return len;
}
};


解题代码二(从前往后扫描):

// 顺序扫描,记录每个 word 的长度
// 时间复杂度 O(n),空间复杂度 O(1)
class Solution {
public:
int lengthOfLastWord(const string& s) {
int len = 0;
for (int i = 0; i < s.size(); ) {
if (s[i] != ' ') ++len, ++i;
else {
++i;
if (i < s.size() && s[i] != ' ') ++len;
}
}
return len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: