Leetcode 58. Length of Last Word
Given a string s
consisting of words and spaces, return the length of the last word in the string.
A word is a maximal sub-string consisting of non-space characters only.
Q: What should be returned if the string is empty or contains only spaces?
A: For an empty string or a string with only spaces, the expected output should be 0
since there are no words.
Q: Are there any constraints on the input string length? A: Usually, strings in such problems can be reasonably assumed to be within typical constraints, like up to (10^4) characters.
#include <iostream>
#include <string>
#include <algorithm> // for std::find_if
int lengthOfLastWord(const std::string &s) {
int length = 0;
int i = s.size() - 1;
// Skip trailing spaces
while (i >= 0 && s[i] == ' ') --i;
// Count length of last word
while (i >= 0 && s[i] != ' ') {
--i;
++length;
}
return length;
}
int main() {
std::string test1 = "Hello World";
std::string test2 = " fly me to the moon ";
std::string test3 = "luffy is still joyboy";
std::string test4 = " ";
std::cout << lengthOfLastWord(test1) << std::endl; // Output: 5
std::cout << lengthOfLastWord(test2) << std::endl; // Output: 4
std::cout << lengthOfLastWord(test3) << std::endl; // Output: 6
std::cout << lengthOfLastWord(test4) << std::endl; // Output: 0
return 0;
}
s
. This is because, in the worst case, we may need to traverse the entire string to skip leading spaces and count the length of the last word.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?