[LeetCode] 58. Length of Last Word
Problem Statement:
Given a string s consisting of words and spaces, return the length of the last word in the string.
Link: https://leetcode.com/problems/length-of-last-word/description/
Brute-force Approach:
- Using .split() method, we will tokenize the string into an array.
- Using a loop, we will iterate through each element from the reverse.
- If length of the element is not equal to 0, return the length of the element.
- To handle edge cases where string is one letter only, we will return 1.
Brute-force Solution:
Brute-force Approach #2:
- Without using any in-built methods, we will traverse the string from reverse ignoring any whitespace.
- From the end, we will start the pointer and keep decrementing the pointer until we reach a character which is not a space.
- Once there, we will increment a length variable until we don't reach a space character.
Approach #2 Solution:
Comments
Post a Comment