diff --git a/solutions/3101-3200/3110-score-of-a-string/README.md b/solutions/3101-3200/3110-score-of-a-string/README.md new file mode 100644 index 0000000..b999986 --- /dev/null +++ b/solutions/3101-3200/3110-score-of-a-string/README.md @@ -0,0 +1,11 @@ +# 3110. Score of a String + +[LeetCode problem 3110](https://leetcode.com/problems/score-of-a-string/) + +- **Difficulty**: Easy +- **Tags**: string + +## Description + +Given a string `s`, its score is the sum of the absolute difference between +the ASCII values of every pair of adjacent characters. diff --git a/solutions/3101-3200/3110-score-of-a-string/solution.cpp b/solutions/3101-3200/3110-score-of-a-string/solution.cpp new file mode 100644 index 0000000..9aa3344 --- /dev/null +++ b/solutions/3101-3200/3110-score-of-a-string/solution.cpp @@ -0,0 +1,19 @@ +#include "solution.hpp" + +#include +#include + +namespace leetcode::p3110 { + +int solve(const std::string& s) { + int score = 0; + + for (int i = 0; i + 1 < std::ssize(s); ++i) { + score += std::abs(static_cast(s.at(static_cast(i))) - + static_cast(s.at(static_cast(i) + 1))); + } + + return score; +} + +} // namespace leetcode::p3110 diff --git a/solutions/3101-3200/3110-score-of-a-string/solution.hpp b/solutions/3101-3200/3110-score-of-a-string/solution.hpp new file mode 100644 index 0000000..b502954 --- /dev/null +++ b/solutions/3101-3200/3110-score-of-a-string/solution.hpp @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace leetcode::p3110 { + +// optimized: O(n) time, O(1) space — sum |s[i] - s[i+1]| over adjacent +// characters. +int solve(const std::string& s); + +} // namespace leetcode::p3110 diff --git a/solutions/3101-3200/3110-score-of-a-string/test.cpp b/solutions/3101-3200/3110-score-of-a-string/test.cpp new file mode 100644 index 0000000..5d96bff --- /dev/null +++ b/solutions/3101-3200/3110-score-of-a-string/test.cpp @@ -0,0 +1,8 @@ +#include + +#include "solution.hpp" + +TEST_CASE("Problem 3110", "[p3110]") { + CHECK(leetcode::p3110::solve("hello") == 13); + CHECK(leetcode::p3110::solve("zaz") == 50); +} diff --git a/swift/3110.swift b/swift/3110.swift deleted file mode 100644 index 5493960..0000000 --- a/swift/3110.swift +++ /dev/null @@ -1,24 +0,0 @@ -func scoreOfString(_ s: String) -> Int { - var score = 0 - - let characters = Array(s) - for i in 0..