本文介绍了一个有趣的数列问题——Count and Say,并分别用C++和Python两种语言实现了该问题的解决方案。Count and Say数列是这样定义的:以数字1开始,之后每一项都是对前一项的描述。例如第一项为1,第二项是对1的描述“1个1”,即11,第三项是对11的描述“2个1”,即21。
class Solution {
public:
stringcountAndSay(int n) {
if (n < 0) return"";
string cur = "1";
while (--n>0){
int st = 0;
int ed = 0;
string tmp="";
while (st<cur.size() && ed<cur.size()){
int cnt = 0;
while (ed<cur.size() && cur[st] == cur[ed]) {
cnt++;
ed++;
}
tmp.push_back(cnt + '0');
tmp.push_back(cur[st]);
st = ed;
//ed = st;
}
cur = tmp;
}
return cur;
}
};
python
classSolution(object):defcountAndSay(self, n):"""
:type n: int
:rtype: str
"""if n <0: return0
cur = '1'while n>1:
n -= 1
tmp = []
st,ed =0,0while st<len(cur) and ed<len(cur):
cnt=0while ed<len(cur) and cur[st]==cur[ed]:
cnt += 1
ed += 1
tmp.append(str(cnt))
tmp.append(cur[st])
st = ed
cur = ''.join(tmp)
return cur