本文主要是介绍leetcode-38 count and say,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目的意思有点迷惑,正确的理解如下:
At the beginning, I got confusions about what is the nth sequence. Well, my solution is accepted now, so I'm going to give some examples of nth sequence here. The following are sequence from n=1 to n=10:
1. 12. 113. 214. 12115. 111221 6. 3122117. 131122218. 11132132119. 3113121113122110. 13211311123113112211
From the examples you can see, the (i+1)th sequence is the "count and say" of the ith sequence!
从discuss中发现了一种很好的算法:
char *countAndSay(int n) {int i,j,k;char tmp[10240];char res[10240] = "1";for(i = 2; i <= n; i++){int count = 1;char digit = res[0];k = 0;for(j = 1; j < strlen(res); j++){if(res[j] == digit)count++;else{tmp[k++] = count + '0';tmp[k++] = digit;digit = res[j];count = 1;}}tmp[k++] = count + '0';tmp[k++] = digit;strncpy(res,tmp,k);}return res;
}
注意产生的串会很长的,所以数组tmp和res的长度要足够用(1024不够,如果使用1024,则一直runtime error)
char str[1024] = "1";
则strlen(str)的值为1;
sizeof(str)的值为1024;
这篇关于leetcode-38 count and say的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!