diff --git a/solutions/0001-0100/0058-length-of-last-word/README.md b/solutions/0001-0100/0058-length-of-last-word/README.md new file mode 100644 index 0000000..de393a7 --- /dev/null +++ b/solutions/0001-0100/0058-length-of-last-word/README.md @@ -0,0 +1,11 @@ +# 58. Length of Last Word + +[LeetCode problem 58](https://leetcode.com/problems/length-of-last-word/) + +- **Difficulty**: Easy +- **Tags**: string + +## Description + +Given a string `s` of words and spaces, return the length of the last word +(a maximal substring of non-space characters). diff --git a/solutions/0001-0100/0058-length-of-last-word/solution.cpp b/solutions/0001-0100/0058-length-of-last-word/solution.cpp new file mode 100644 index 0000000..52fc1f6 --- /dev/null +++ b/solutions/0001-0100/0058-length-of-last-word/solution.cpp @@ -0,0 +1,21 @@ +#include "solution.hpp" + +namespace leetcode::p0058 { + +int solve(const std::string& s) { + int i = static_cast(s.size()) - 1; + + while (i >= 0 && s.at(static_cast(i)) == ' ') { + --i; + } + + int length = 0; + while (i >= 0 && s.at(static_cast(i)) != ' ') { + ++length; + --i; + } + + return length; +} + +} // namespace leetcode::p0058 diff --git a/solutions/0001-0100/0058-length-of-last-word/solution.hpp b/solutions/0001-0100/0058-length-of-last-word/solution.hpp new file mode 100644 index 0000000..cdfb28e --- /dev/null +++ b/solutions/0001-0100/0058-length-of-last-word/solution.hpp @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace leetcode::p0058 { + +// optimized: O(n) time, O(1) space — scan backward from the end, skipping +// trailing spaces then counting the last word. +int solve(const std::string& s); + +} // namespace leetcode::p0058 diff --git a/solutions/0001-0100/0058-length-of-last-word/test.cpp b/solutions/0001-0100/0058-length-of-last-word/test.cpp new file mode 100644 index 0000000..4f9dda8 --- /dev/null +++ b/solutions/0001-0100/0058-length-of-last-word/test.cpp @@ -0,0 +1,9 @@ +#include + +#include "solution.hpp" + +TEST_CASE("Problem 58", "[p0058]") { + CHECK(leetcode::p0058::solve("Hello World") == 5); + CHECK(leetcode::p0058::solve(" fly me to the moon ") == 4); + CHECK(leetcode::p0058::solve("luffy is still joyboy") == 6); +} diff --git a/typescript/lengthOfLastWord.ts b/typescript/lengthOfLastWord.ts deleted file mode 100644 index f6ccca7..0000000 --- a/typescript/lengthOfLastWord.ts +++ /dev/null @@ -1,5 +0,0 @@ -function lengthOfLastWord(s: string): number { - const strSplited = s.trim().split(" "); - const lastWord = strSplited[strSplited.length - 1]; - return lastWord.length; -}