首页 > 代码库 > Leetcode#38 Count and Say

Leetcode#38 Count and Say

原题地址

 

简单模拟题

从1开始推即可。不知道有没有规律可以直接求出n

 

代码:

 1 string countAndSay(int n) { 2         if (n <= 0) 3             return ""; 4              5         string str = "1"; 6         while (--n) { 7             string next; 8             int count = 1; 9             char last = str[0];10             for (int i = 1; i < str.length(); i++) {11                 if (str[i] == last)12                     count++;13                 else {14                     next += count + 0;15                     next += last;16                     last = str[i];17                     count = 1;18                 }19             }20             next += count + 0;21             next += last;22             str = next;23         }24         25         return str;26 }

 

Leetcode#38 Count and Say