-
Notifications
You must be signed in to change notification settings - Fork 118
/
Look and Say Sequence.cpp
52 lines (43 loc) · 1.24 KB
/
Look and Say Sequence.cpp
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
43
44
45
46
47
48
49
50
51
52
#include <bits/stdc++.h>
using namespace std;
// generator function returns int string from prev int
// string e.g. -> it will return '1211' for '21' ( One 2's
// and One 1)
string generator(string str)
{
string ans = "";
unordered_map<char, int>
tempCount; // It is used to count integer sequence
for (int i = 0; i < str.length() + 1; i++) {
// when current char is different from prev one we
// clear the map and update the ans
if (tempCount.find(str[i]) == tempCount.end()
&& i > 0) {
auto prev = tempCount.find(str[i - 1]);
ans += to_string(prev->second) + prev->first;
tempCount.clear();
}
// when current char is same as prev one we increase
// it's count value
tempCount[str[i]]++;
}
return ans;
}
string countnndSay(int n)
{
string res = "1"; // res variable keep tracks of string
// from 1 to n-1
// For loop iterates for n-1 time and generate strings
// in sequence "1" -> "11" -> "21" -> "1211"
for (int i = 1; i < n; i++) {
res = generator(res);
}
return res;
}
int main()
{
int N ;
cin >> N;
cout << countnndSay(N) << endl;
return 0;
}