The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
is read off as one 1
or 11
.11
is read off as two 1s
or 21
.21
is read off as one 2, then one 1
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Example:
if
the sequence is
n = 2
,the sequence is
11
. string appendNext(string str){
string out = "";
char curr = str[0];
int currCount = 1;
for(int i = 1; i < str.size(); i++){
if (str[i] == curr){
currCount++;
}
else {
char chr = currCount + '0';
out = out + chr;
out = out + curr;
curr = str[i];
currCount = 1;
}
}
char chr = currCount + '0';
out = out + chr;
out = out + curr;
return out;
}
string Solution::countAndSay(int n) {
if (n == 1) {
return "1";
}
string prev = "1";
string result;
for (int i = 1; i < n; i++){
result = appendNext(prev);
prev = result;
}
return result;
}
Last but not least, online college science classes will encourage the trait of being self-motivated. artificial intelligence course in hyderabad
ReplyDelete