From 828f3e0e7b7c2df24a7dc1021c32b4a9efed176e Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Thu, 27 Feb 2025 00:33:36 +0800 Subject: [PATCH] feat: 38_count_and_say --- 38_count_and_say/main.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 38_count_and_say/main.cpp diff --git a/38_count_and_say/main.cpp b/38_count_and_say/main.cpp new file mode 100644 index 0000000..3e71d60 --- /dev/null +++ b/38_count_and_say/main.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +class Solution { + public: + string rle(string s) { + s.push_back('.'); + + string result; + int sameCount = 1; + + for (int i = 1; i < s.length(); i++) { + if (s[i] == s[i - 1]) { + sameCount++; + } else { + result.append(to_string(sameCount) + to_string(s[i - 1] - '0')); + sameCount = 1; + } + } + + return result; + } + + string countAndSay(int n) { + string result = "1"; + for (int i = 1; i < n; i++) { + result = rle(result); + } + return result; + } +};