Skip to content

Commit

Permalink
Popular leetcode problem, count and say
Browse files Browse the repository at this point in the history
  • Loading branch information
sujayshanbhag committed Oct 20, 2023
1 parent 62a1a54 commit 60da9b3
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions strings/C++/CountAndSay.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include <iostream>
#include <string>

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;
}

0 comments on commit 60da9b3

Please sign in to comment.