About Count and say topics
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.
One is read off as "1s" or 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 would be represented as a string.s
Solution One: Iteration
The idea is to traverse the character of the previous string, and if the previous character equals the current character, increment the count, otherwise output to res and initialize the counter.
This method removes the same elements in the array as before.
stringCountandsay (int n) {if(n==0)return "";stringPrev ="1";stringres =""; IntCount=1; for(int i=1; i<n;i++) { for(int j=1; J<=prev.length(); j + +) {if(J==prev.length()) {cout<<i<<": "<<prev[j]<<endl; }if(prev[j-1]==prev[j]) {Count++; }Else{res + = to_string (Count); Res + = prev[j-1];Count=1; }} prev = res; res =""; /* ~~my Own Stupid Code ~~s ch = prev[0];Count=1; for(int j=1; J<prev.length(); j + +) { while(Ch==prev[j]) {Count++; j + +; } Res + =Count; res + = ch; ch = prev[j];Count=1; } prev = res; res =""; cout<<i+1<<" "<<res; */ }returnPrev }
Solution Two: Recursion
stringCountandsay (intN) {if(n==1) return"1";stringprev = Countandsay (n1);int Left=0;int Right=0;stringres =""; while( Left<prev.length ()) { while(prev[ Left]==prev[ Right]) Right++; Res + = to_string ( Right- Left) + prev[ Left]; Left= Right; } return res; }s
Summarize
At first, when I was thinking about the problem, I didn't think of recursion, and using recursion would simplify the code and get a better understanding.
There are a few considerations when using the iterative approach:
1. Note the boundary value
-Traversal times from 1 to n-1: int i=1;i<n;i++
;
-Each string traversal: for(int j=1;j<=prev.length();j++)
;
-For the string prev[length] is \0
2. You do not need to define a single char to store the current character
3. Logic is very simple, simply is better.
Leetcode-38. Count and Say