Count and Say Solutions in C++
Number 38
Difficulty Easy
Acceptance 44.7%
Link LeetCode
Other languages Java
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/count-and-say/// Author : Hao Chen// Date : 2014-07-03#include <stdlib.h>#include <iostream>#include <sstream>#include <string>#include <vector>using namespace std;string vecToStr(vector<int> v) {stringstream ss;for (int i=0; i<v.size(); i++) {ss << v[i];}return ss.str();}vector<int> getNext(vector<int>& v) {int cnt=0;int val=0;vector<int> ret;for(int i=0; i<v.size(); i++){if (i==0){val = v[i];cnt = 1;continue;}if (v[i] == val){cnt++;}else{ret.push_back(cnt);ret.push_back(val);val = v[i];cnt = 1;}}if (cnt>0 && val>0){ret.push_back(cnt);ret.push_back(val);}return ret;}string countAndSay(int n) {if (n<=0) return "";if (n==1) return "1";string s;vector<int> v;v.push_back(1);for(int i=2; i<=n; i++){v = getNext(v);//s = s + ", " +vecToStr(v);}s = vecToStr(v);return s;}int main(int argc, char** argv){int n = 4;if (argc>1){n = atoi(argv[1]);}cout << countAndSay(n) << endl;return 0;}
C++ solution by pezy/LeetCode
#include <string>using std::string;class Solution {public:string countAndSay(int n) {string ret{"1"};for (int i=0; i<n-1; ++i) {string str;auto b = ret.cbegin();for (auto e=b; e != ret.cend(); ++e)if (*b != *e) { str += std::to_string(e-b) + *b; b = e; }ret = str + std::to_string(ret.cend()-b) + *b;}return ret;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/count-and-say/description//// Author : liuyubobobo/// Time : 2018-10-03#include <iostream>using namespace std;/// Simulation/// Time Complexity: O(n * 2^n)/// Space Complexity: O(2^n)class Solution {public:string countAndSay(int n) {string s = "1";if(n == 1)return s;for(int i = 2; i <= n; i ++)s = next(s);return s;}private:string next(const string& s){string ret = "";int start = 0;for(int i = start + 1; i <= s.size(); i ++)if(i == s.size() || s[i] != s[start]){ret += to_string(i - start) + s[start];start = i;}return ret;}};int main() {cout << Solution().countAndSay(1) << endl;cout << Solution().countAndSay(2) << endl;cout << Solution().countAndSay(3) << endl;cout << Solution().countAndSay(4) << endl;cout << Solution().countAndSay(5) << endl;cout << Solution().countAndSay(30) << endl;return 0;}