# Most concise solution

• uses 2 swapping buffers: one to hold the current string, and the other the next string. Also uses the result that count < 4, as found by others.

``````#include<cstring>
class Solution {
public:
string countAndSay(int n) {
string s1("1"),s2,*p1 = &s2, *p2=&s1;
int i,j;
for(i=1;i<n;i++){
swap(p1,p2);
p2->clear();
p1->append(1,0);
char prev=(*p1)[0];
int count=0;
for(char cur : *p1){
if(cur!=prev){
*p2 += '0'+count;
*p2 += prev;
count=0;
}
count++;
prev=cur;
}

}
return *p2;
}
};``````

• This post is deleted!

• This post is deleted!

• This post is deleted!

• ``````// use string.swap()
string countAndSay(int n) {
string s = "1", t;
for(int i = 1; i < n; ++i){
for(string::const_iterator p = s.begin(), pe = s.end(); p != pe; ){
char c = *p++;
int cnt = 1;
while(p != pe && *p == c){
++p;
++cnt;
}
t += '0' + cnt;
t += c;
}
s.swap(t);
t.clear();
}
return s;
}``````

• Python code is conciser:

``````class Solution:
# @return a string
def countAndSay(self, n):
if n <= 1:
return '1'
prev, count = None, 0
result = []
for x in self.countAndSay(n-1):
if prev is None or prev == x:
prev = x
count += 1
else:
result.append(str(count))
result.append(prev)
prev = x
count = 1
result.append(str(count))
result.append(prev)
return ''.join(result)``````

• You're using recursion, not as efficient. The number lines is the same excluding the braces on their own lines.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.