15 Jun 2024C++ / Python / TypeScriptEasy

Length of Last Word

Collected C++, Python, TypeScript solutions for length of last word. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Length of Last Word. the solution files are available below.

solution files

  • C++ length-of-last-word/synced-solution.cpp
  • Python length-of-last-word/synced-solution.py
  • TypeScript length-of-last-word/synced-solution.ts

Solution files

Pythonlength-of-last-word/synced-solution.py
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.rstrip().split()[-class="syntax-number">1])
C++length-of-last-word/synced-solution.cpp
class Solution {
public:
    int lengthOfLastWord(string s) {
        int len = class="syntax-number">0, i = s.size()-class="syntax-number">1;
        while (i >= class="syntax-number">0 && s[i] == class="syntax-string">' ') i--;
        while (i >= class="syntax-number">0 && s[i] != class="syntax-string">' ') { len++; i--; }
        return len;
    }
};
TypeScriptlength-of-last-word/synced-solution.ts
function lengthOfLastWord(s: string): number {
    return s.trimEnd().split(class="syntax-string">' ').pop()!.length;
}