The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1
is read off as "one 1"
or 11
.11
is read off as "two 1s"
or 21
.21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
好奇怪的一道题目,意思是数(三)数(四).把数字用口头语言说出来,1就是1,2前面是1就是1一个(11),3前面2个1就是(21),然后是(1211),再是(111221)以此类推。。。 当时题目看了半天没看懂,又去别的地方查了下题目是什么意思才知道了:
1 class Solution { 2 public: 3 string countAndSay(int n) { 4 string curr = ""; 5 if(n <= 0) return curr; 6 curr = "1"; 7 for(int i = 1; i < n; ++i){ 8 curr = convert(curr); 9 } 10 return curr; 11 } 12 13 string convert(const string & prev){ 14 //string result = ""; 15 stringstream result; 16 char last = prev[0]; 17 int count = 0; 18 int sz = prev.size(); 19 for(int i = 0; i <= sz; ++i){//注意是<= 20 if(prev[i] == last) 21 count++; 22 else{ 23 result << count << last; 24 // result.append(count); 这里append无法实现,因为找不到itoa,很蛋疼,只能用stream来实现 25 // result.append(last); 26 last = prev[i]; 27 count = 1; 28 } 29 } 30 return result.str(); 31 } 32 };
下面是java版本的,用了双指针,方法和上面的还是有一点不一样的:
1 public class Solution { 2 public String countAndSay(int n) { 3 String s = String.valueOf(1);//很方便,直接就有类似itoa的api 4 for(int i = 1; i < n; ++i){ 5 s = say(s); 6 } 7 return s; 8 } 9 10 public String say(String s){ 11 int sz = s.length(); 12 int p2 = 0, p1 = 0; 13 int count = 0; 14 String ret = new String(""); 15 while(p1 < sz){ 16 while(s.charAt(p1) == s.charAt(p2)){ 17 p1++; 18 if(p1 == sz) //检查如果超过了长度就退出 19 break; 20 } 21 count = p1 - p2; 22 ret = ret + String.valueOf(count) + s.charAt(p2); 23 p2 = p1;//更新p2 24 } 25 return ret; 26 } 27 }