给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = “Hello World”
输出:5
解释:最后一个单词是“World”,长度为5。
示例 2:
输入:s = “ fly me to the moon “
输出:4
解释:最后一个单词是“moon”,长度为4。
示例 3:
输入:s = “luffy is still joyboy”
输出:6
解释:最后一个单词是长度为6的“joyboy”。
方法一:从左到右顺序遍历
双指针记录单词开头和结尾,单词开头为空字符串后的第一个字符;单词结尾为单词开头往后遍历直到碰到空格为止
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: int lengthOfLastWord(string s) { int pre = 0; int start = 0, end = 0; while (start < s.size() && end < s.size()) { if (s[start] == ' ') { start++; }else{ end = start; while(end < s.size() && s[end] != ' '){ end++; } pre = end - start; cout << "pre:" << pre << endl; start = end; } } return pre; } };
|
方法二:从后向左遍历
如果最右边为空格,需要跳过
从最右边第一个非空字符开始向左遍历,直到碰到空格或者左边界为止。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: int lengthOfLastWord(string s) { int end = s.size() - 1, start = 0, ans = 0; while (end >= 0 && s[end] == ' ') end--; if (end >=0 && s[end] != ' '){ start = end; while(start >=0 && s[start] != ' ') start--; ans = end - start; } return ans; } };
|