Given a string
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing
the relative positions of the remaining characters. (i.e.,
Output: 5
Explanation: the last word in input string is "World" with length 5.
Output: 4
Explanation: The last word is "moon" with length 4.
Output: 6
Explanation: The last word is "joyboy" with length 6.
Contents
Solution using trace the last word from right side and return its length
In this approach, we are going to start from right end of the string and find where the last word starts (without any spaces) and calculate its length.
-
We will create a function
traceFromRightSide that takes input argument strings . -
Base case is, if the length of
s is greater than length oft , then we can simply returnfalse . -
Declare a variable
length = 0 to store length of last word. -
Then, start tracing from right end of the input string
s and start incrementinglength value, when we find a non space character until a next space is found and exit the program. -
Finally, return
length , which holds the length of last word.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1) since we are using just
Above implementations source code can be found at