From 60da9b31db1ea4d4103dfaf000384747a030a92a Mon Sep 17 00:00:00 2001 From: SujayShanbhag Date: Fri, 20 Oct 2023 16:18:51 +0530 Subject: [PATCH] Popular leetcode problem, count and say --- strings/C++/CountAndSay.cpp | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 strings/C++/CountAndSay.cpp diff --git a/strings/C++/CountAndSay.cpp b/strings/C++/CountAndSay.cpp new file mode 100644 index 000000000..2ef168081 --- /dev/null +++ b/strings/C++/CountAndSay.cpp @@ -0,0 +1,39 @@ +#include +#include + +class Solution { +public: + std::string countAndSay(int n) { + std::string prev = "1"; + for (int i = 2; i <= n; i++) { + char val = prev[0]; + int count = 1; + std::string cur = ""; + for (int j = 1; j < prev.length(); j++) { + if (prev[j] != val) { + cur += std::to_string(count) + val; + val = prev[j]; + count = 1; + } else { + count++; + } + } + cur += std::to_string(count) + val; + prev = cur; + } + return prev; + } +}; + +int main() { + int n; + std::cout << "Enter a value of n: "; + std::cin >> n; + + Solution solution; + std::string result = solution.countAndSay(n); + + std::cout << "The " << n << "th term in the count-and-say sequence is: " << result << std::endl; + + return 0; +}