58. Length of Last Word leetcode solution in c++
int lengthOfLastWord(string s) {
int length = 0;
int i = s.size() - 1;
while (i >= 0 && s[i] == ' ') {
i--;
}
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
Explanation:
- We start by initializing the
length
variable to 0. This variable will store the length of the last word in the given strings
. - We initialize
i
tos.size() - 1
, which is the last index of the strings
. - We enter a
while
loop that checks two conditions:i
should be greater than or equal to 0, and the character at indexi
in the strings
should be a space' '
. This loop helps us skip any trailing spaces at the end of the string. - Inside the loop, we decrement
i
by 1 to move to the previous character. - After the loop ends, we have skipped all the trailing spaces at the end of the string.
- We enter another
while
loop that checks two conditions:i
should be greater than or equal to 0, and the character at indexi
in the strings
should not be a space' '
. This loop helps us count the length of the last word. - Inside the loop, we increment the
length
variable by 1 to count the current character. - We decrement
i
by 1 to move to the previous character. - After the loop ends, we have counted the length of the last word in the string.
- We return the
length
variable as the result.
This solution iterates through the string s
from the end, skipping any trailing spaces and counting the length of the last word. It has a time complexity of O(n), where n is the length of the string s
.