Leetcode 38 Count and Say Solution in java | Hindi Coding Community

0

 


The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

countAndSay(1) = "1"

countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you "say" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.


For example, the saying and conversion for digit string "3322251"




class Solution {
public:
string countAndSay(int n) {
string num = "1";
for (int i = 1; i < n; i++) {
num = say(num);
}
return num;
}
private:
string say(string num) {
int n = num.size();
string s;
for (int i = 0, j = 1, k = 1; i < n; i = j, j = i + 1, k = 1) {
while (j < n && num[j] == num[i]) {
j++;
k++;
}
s += char(k + '0');
s += num[i];
}
return s;
}
};



Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !