-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountAndSay.cpp
More file actions
42 lines (42 loc) · 983 Bytes
/
countAndSay.cpp
File metadata and controls
42 lines (42 loc) · 983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<vector>
int countFreq(const std::string &str, int &index){
char ch = str[index];
int freq = 0;
while(index<str.size() && str[index]==ch){
++index;
++freq;
}
return freq;
}
std::string countAndSay(int A){
if(A==1){
return "1";
}
if(A==2){
return "11";
}
std::string prev = "11";
for(int index = 3;index<=A;++index){
//fill dp[index] using dp[index-1];
//std::string prev = dp[index-1];
std::string curr = "";
int j = 0;
while(j<prev.length()){
char ch = prev[j];
int freq = countFreq(prev, j);
//std::cout<<ch<<" "<<freq<<std::endl;
curr+=std::to_string(freq);
curr+=std::to_string(ch - '0');
}
prev = curr;
}
return prev;
}
int main(){
int A;
std::cin>>A;
std::string output = countAndSay(A);
std::cout<<output<<std::endl;
return 0;
}