public class Solution { public string CountAndSay(int n) { //1 //11 //21 //1211 //111221 //312211 //13112221 //1113213211 if (n == 1) { return "1"; } else { var list = new List<string>(); list.Add("1"); var result = ""; var pre = ""; for (int i = 1; i < n; i++) { pre = list[i - 1]; var c = pre[0]; var newrow = new StringBuilder(); var count = 1; for (int j = 1; j < pre.Length; j++) { var cur = pre[j]; if (c != cur) { newrow.Append(count).Append(c); count = 1; c = cur; } else { count++; } } newrow.Append(count).Append(c); list.Add(newrow.ToString()); } result = list[list.Count - 1]; return result; } } }
https://leetcode.com/problems/count-and-say/#/description
补充一个python的实现:
1 class Solution: 2 def countAndSay(self, n: int) -> str: 3 if n == 1: 4 return '1' 5 else: 6 l = []#定义n=1,2,3……时对应的字符串 7 l.append('1')#第0位固定是'1' 8 result = ''#定义用于存储最终结果的字符串 9 pre = ''#定义上一个字符串 10 for i in range(1,n):#外层循环,从index=1开始 11 pre = l[i-1]#n取前一个值的时候,得到的字符串 12 c = pre[0]#前一个字符串的第0位 13 newrow = ''#空行 14 count = 1#计数器为1 15 for j in range(1,len(pre)):#遍历前一个字符串,从index=1开始 16 cur = pre[j]#当前位置的字符 17 if c != cur:#如果当前字符和前一个字符不想等,例如'21' 18 newrow += str(count)#新字符串+'1' 19 newrow += c#新字符串+'2' 20 count = 1#计数器归1 21 c = cur#c更新为当前值cur 22 else: 23 count += 1#两个字符相同,例如'11',则计数器+1 24 newrow += str(count)#新字符串+count 25 newrow += c#新字符串+c 26 l.append(newrow)#n在当前取值时的字符串已经生成完毕,添加到集合l中 27 result = l[-1]#集合最后一个元素,就是n取最后一个值时生成的字符串 28 return result