您的位置:首页 > 编程语言 > C语言/C++

Count and Say

2016-06-11 22:46 351 查看

c++

class Solution {
public:
string countAndSay(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

class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n <0: return 0
cur = '1'
while n>1:
n -= 1

tmp = []
st,ed =0,0
while st<len(cur) and ed<len(cur):
cnt=0
while 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言