classSolution { public: string cal(string &s){ string ans = ""; int cnt =1; int len = s.length(); for (int i = 0; i < len; i++) { if (i + 1 < len && s[i] != s[i + 1]){ ans = ans + char(cnt+48) + s[i]; cnt = 1; } elseif (i + 1 < len) cnt++; } ans = ans + char(cnt+48) + s[len-1]; return ans; } string countAndSay(int n){ string s = "1"; for (int i = 1; i < n; i++) s = cal(s); return s; } };
classSolution: # @return a string defcountAndSay(self, n): s='1' for i inrange(1,n): s=self.cal(s) return s defcal(self,s): cnt=1 length=len(s) ans='' for i ,c inenumerate(s): if i+1 < length and s[i]!=s[i+1]: ans=ans+str(cnt)+c cnt=1 elif i+1 <length: cnt=cnt+1 ans=ans+str(cnt)+c return ans