LintCode: Count and Say
C++
1 class Solution { 2 public: 3 /** 4 * @param n the nth 5 * @return the nth sequence 6 */ 7 string countAndSay(int n) { 8 // Write your code here 9 if (0 == n) { 10 return ""; 11 } 12 string pre = "1"; 13 for (int i = 1; i < n; i++) {//从第2个(i=1)开始 14 char ch = pre[0]; 15 string cur = ""; 16 int cnt = 0; 17 for (int j = 0; j < pre.size(); j++) { 18 if (pre[j] == ch) { 19 cnt ++; 20 } else { 21 cur = cur + itostr(cnt) + ch; 22 ch = pre[j]; 23 cnt = 1; 24 } 25 } 26 if (cnt != 0) {//处理后边的字符 27 cur = cur + itostr(cnt) + ch; 28 } 29 pre = cur; 30 cur = ""; 31 } 32 return pre; 33 34 } 35 string itostr(int i) {//自定义int转string函数 36 char str[10]; 37 //itoa(str,i,10);->only support Windows 38 sprintf(str, "%d", i);//support any platforms 39 return str; 40 } 41 };
 
找我内推:    字节跳动各种岗位
  
  
  作者:
  
    ZH奶酪(张贺)
  
  
邮箱:
  
    cheesezh@qq.com
  
  
  出处:
  
    http://www.cnblogs.com/CheeseZH/
  
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号