大纲
- 题目
- 地址
- 内容
- 解题
- 代码地址
题目
地址
https://leetcode.com/problems/length-of-last-word/description/
内容
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = “Hello World”
Output: 5
Explanation: The last word is “World” with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is “moon” with length 4.
Example 3:
Input: s = “luffy is still joyboy”
Output: 6
Explanation: The last word is “joyboy” with length 6.
Constraints:
- 1 <= s.length <= 104
- s consists of only English letters and spaces ’ '.
- There will be at least one word in s.
解题
这题就是要找到一个字符串中最后一段非空格的连续字符长度。我们只要定义好这样的子串特点即可:以空格后的第一个字符开始,以空格前的最后一个字符结束。向后遍历,找到最后一个符合这个特点的子串。需要注意的是两个边界:我们可以假设原始字符串前有一个空格,原始字符串后有一个空格,这可以保证我们逻辑的一致性。
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
bool preIsSpace = true; // if the previous character is space
int cur = 0;
int lastWordStart = 0;
int lastWordEnd = 0;
for (char c : s) {
if (c == ' ') {
if (!preIsSpace) {
lastWordEnd = cur;
}
preIsSpace = true;
} else {
if (preIsSpace) {
lastWordStart = cur;
}
preIsSpace = false;
}
cur++;
}
if (!preIsSpace) {
lastWordEnd = cur;
}
return lastWordEnd - lastWordStart;
}
};
代码地址
https://github.com/f304646673/leetcode/tree/main/58-Length-of-Last-Word