LeetCode【38】 Count and Say
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.
题目看了半天,对自己的汉语水平狠狠的质疑了一把,然后开始写代码。
string countAndSay1(int n) { if(n<=0) return ""; string str="1"; for(int i =1;i<n;i++) { int count=0; string tmp=""; for(int j =0,k=0;k<str.size();k++) { char chj=str[j]; char chk=str[k]; if(chj==chk) count++; else { tmp=tmp+(char)(count+'0')+chj; j=k; count=1; } } tmp=tmp+(char)(count+'0')+str[str.size()-1]; str = tmp; } return str; }
完了再去看别人写的代码,发现差距还是有的,自己这乱糟糟的风格,简单的东西非要那么复杂干什么。。自己努力学着点,学着短小精悍!
string s = "1"; for(int i = 1; i < n; ++ i) { int count = 1; string temp = ""; for(int j = 1; j < s.size(); ++ j) { if(s[j] == s[j - 1]) ++ count; else { temp = temp + (char)(count + '0') + s[j - 1]; count = 1; } } s = temp + (char)(count + '0') + s[s.size() - 1]; } return s;