From 8ce5ca9166fce16ef5e9909b68a0a9005ba9579b Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 22 Nov 2022 18:06:14 +0800 Subject: [PATCH] s0038 --- include/s0038_count_and_say.hpp | 14 ++++++++++++++ src/s0038_count_and_say.cpp | 21 +++++++++++++++++++++ tests/s0038_count_and_say.cpp | 17 +++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 include/s0038_count_and_say.hpp create mode 100644 src/s0038_count_and_say.cpp create mode 100644 tests/s0038_count_and_say.cpp diff --git a/include/s0038_count_and_say.hpp b/include/s0038_count_and_say.hpp new file mode 100644 index 0000000..d9a040f --- /dev/null +++ b/include/s0038_count_and_say.hpp @@ -0,0 +1,14 @@ +#ifndef S0038_COUNT_AND_SAY_HPP +#define S0038_COUNT_AND_SAY_HPP + +#include +#include + +using namespace std; + +class Solution { + public: + string countAndSay(int n); +}; + +#endif diff --git a/src/s0038_count_and_say.cpp b/src/s0038_count_and_say.cpp new file mode 100644 index 0000000..a11ba97 --- /dev/null +++ b/src/s0038_count_and_say.cpp @@ -0,0 +1,21 @@ +#include "s0038_count_and_say.hpp" + +string Solution::countAndSay(int n) { + if (n == 1) { + return "1"; + } else if (n <= 0) { + return ""; + } + string prev = countAndSay(n - 1); + string result{""}; + int len = prev.length(); + int pos{0}, start{0}; + while (pos < len) { + while (pos < len && prev[pos] == prev[start]) { + pos++; + } + result += to_string(pos - start) + prev[start]; + start = pos; + } + return result; +} diff --git a/tests/s0038_count_and_say.cpp b/tests/s0038_count_and_say.cpp new file mode 100644 index 0000000..77cba2c --- /dev/null +++ b/tests/s0038_count_and_say.cpp @@ -0,0 +1,17 @@ +#include "s0038_count_and_say.hpp" + +#include + +TEST(Problem38, Case1) { + int i{1}; + string o{"1"}; + Solution solution; + EXPECT_EQ(solution.countAndSay(i), o); +} + +TEST(Problem38, Case2) { + int i{4}; + string o{"1211"}; + Solution solution; + EXPECT_EQ(solution.countAndSay(i), o); +}