The Length of Last Word solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Length of Last Word
C++, Python and TypeScript solutions for Length of Last Word.
Solution files
Python•length-of-last-word/synced-solution.py
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.rstrip().split()[-1])
C++•length-of-last-word/synced-solution.cpp
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0, i = s.size()-1;
while (i >= 0 && s[i] == ' ') i--;
while (i >= 0 && s[i] != ' ') { len++; i--; }
return len;
}
};
TypeScript•length-of-last-word/synced-solution.ts
function lengthOfLastWord(s: string): number {
return s.trimEnd().split(' ').pop()!.length;
}