Length Of Last Word
Given a string s
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., "ace""abcde""aec"
Example 1
Output: 5
Explanation: the last word in input string is "World" with length 5.
Example 2
Output: 4
Explanation: The last word is "moon" with length 4.
Example 3
Output: 6
Explanation: The last word is "joyboy" with length 6.
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
that takes input argument stringtraceFromRightSide .s -
Base case is, if the length of
is greater than length ofs , then we can simply returnt .false -
Declare a variable
to store length of last word.length = 0 -
Then, start tracing from right end of the input string
and start incrementings value, when we find a non space character until a next space is found and exit the program.length -
Finally, return
, which holds the length of last word.length
public class LengthOfLastWord {
static int traceFromRightSide(String s) {
int length = 0;
for(int i=s.length() -1; i>=0 ; i--) {
if(s.charAt(i) != ' '){
length++;
}
if(s.charAt(i) == ' ' && length != 0) {
return length;
}
}
return length;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where ns
Space complexity: O(1) since we are using just length
Above implementations source code can be found at