Length of last word
58. Length of Last Word
Easy
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal
Example 1:
Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6.
Constraints:
1 <= s.length <= 104sconsists of only English letters and spaces' '.- There will be at least one word in
s.
myCode.py:
- 1
- 2
otherCode.py:
- iterate throughout the list from right to left
- ignore all whitespaces
- when reaching the alphabet character count all adjacent non-whitespace elements and return the result when reaching a whitespace element
class Solution:
def lengthOfLastWord(self, s: str) -> int:
result = 0
for i in range(len(s)-1, -1, -1):
if s[i] != " ":
result += 1
elif result:
return result
return resultCode
class Solution {
public:
int lengthOfLastWord(string s) {
stack<char> s1;
int count=0;
for(int i=0;i<s.size();i++){
s1.push(s[i]);
}
//here we push all the element of the string to stack
/*
now we will pop() all the blank spaces from the top of stack so
that we reach the last later of the last word.
*/
while(s1.top()==' ')s1.pop();
/*
now we run the while loop util the stack is empty in the case of
only one word is there or the blank space comes which seperate the two words.
*/
while(!s1.empty()&&s1.top()!=' '){
count++;
s1.pop();
}
// now we itterate the count to count the length of the last word and return it.
return count;
}
};
Comments
Post a Comment