Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions solutions/0001-0100/0058-length-of-last-word/README.md
Original file line number Diff line number Diff line change
@@ -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).
21 changes: 21 additions & 0 deletions solutions/0001-0100/0058-length-of-last-word/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include "solution.hpp"

namespace leetcode::p0058 {

int solve(const std::string& s) {
int i = static_cast<int>(s.size()) - 1;

while (i >= 0 && s.at(static_cast<std::size_t>(i)) == ' ') {
--i;
}

int length = 0;
while (i >= 0 && s.at(static_cast<std::size_t>(i)) != ' ') {
++length;
--i;
}

return length;
}

} // namespace leetcode::p0058
11 changes: 11 additions & 0 deletions solutions/0001-0100/0058-length-of-last-word/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#pragma once

#include <string>

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
9 changes: 9 additions & 0 deletions solutions/0001-0100/0058-length-of-last-word/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#include <catch2/catch_test_macros.hpp>

#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);
}
5 changes: 0 additions & 5 deletions typescript/lengthOfLastWord.ts

This file was deleted.

Loading