Solution:
This problem is solved with a reverse traversal:
Expect to see this problem in both cases;
- The last one is the word
- The last is a space
for the first case, a direct calculation of the last word in length, then return to;
but this is also divided into two smaller cases,- Finally there is a word in front of the word, it is determined whether or not the last word in a condition to end the current element pointer is a space;
- The last word is not in front of the word, so that the end of the current pointer position of -1;
For the second case, the need to filter out the space, and then calculates; but if the string only spaces, all spaces filtered off, the current pointer position of -1, 0 can be directly returned.
code show as below:
class Solution:
def lengthOfLastWord(self, s):
right = len(s) - 1
while right >= 0:
if s[right] != ' ':
if right == 0:
return 1
count = 0
while s[right] != ' ' and right >= 0:
right -= 1
count += 1
return count
else:
while s[right] == ' ' and right >= 0:
right -= 1
if right == -1:
return 0
return 0
Screenshot Results:
The
IF right == 0:
return. 1
are summarized into the first for loop
class Solution:
def lengthOfLastWord(self, s):
# if len(s) == 1 and s[0] != ' ':
# return 1
# elif len(s) == 1 and s[0] == ' ':
# return 0
right = len(s) - 1
while right >= 0:
if s[right] != ' ':
count = 0
while s[right] != ' ' and right >= 0:
right -= 1
count += 1
return count
else:
while s[right] == ' ' and right >= 0:
right -= 1
if right == -1:
return 0
return 0
Computing first filtering space, and then the word
class Solution:
def lengthOfLastWord(self, s):
end = len(s) - 1
while (end >= 0 and s[end] == ' '):
end -= 1
if end == -1:
return 0
start = end
while start >= 0 and s[start] != ' ':
start -= 1
return end - start