木又连续日更第14天(14/100)html
木又的第66篇leetcode解题报告
python
字符串
类型第9篇解题报告c++
leetcode第38题:报数web
微信
【题目】app
报数序列是一个整数序列,按照其中的整数的顺序进行报数,获得下一个数。其前五项以下:ui
1. 1
2. 11
3. 21
4. 1211
5. 111221
1
被读做 "one 1"
("一个一"
) , 即 11
。11
被读做 "two 1s"
("两个一"
), 即 21
。21
被读做 "one 2"
, "one 1"
("一个二"
, "一个一"
) , 即 1211
。spa
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。.net
注意:整数顺序将表示为一个字符串。3d
示例 1:
输入: 1
输出: "1"
示例 2:
输入: 4
输出: "1211"
【思路】
这道题题意可能不太好理解,下一个值是上一个值的报数:第一个值是‘1’,第二个值是第一个值的报数'11'(1个1),第三个值是第二个值的报数'21'(2个1),第四个值是第三个值的报数'1211'(1个2,1个1),以此类推。
所以,本题实现起来不难,注意考虑边界问题。
【代码】
python版本
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = '1'
if n == 1:
return '1'
for i in range(1, n):
count = 1
tmp = ''
# 统计连续相同字符的个数,加入tmp中
for i in range(1, len(res)):
if res[i] == res[i-1]:
count += 1
else:
tmp += str(count) + res[i-1]
count = 1
tmp += str(count) + res[-1]
res = tmp
return res
C++版本
class Solution {
public:
string countAndSay(int n) {
string res="1";
int count=0;
string tmp;
for(int i=1; i<n; i++){
tmp = "";
count = 1;
// 统计连续相同字符的个数,加入tmp中
for(int j=1; j<res.size(); j++){
if(res[j] == res[j-1])
count++;
else{
tmp += to_string(count) + res[j-1];
count = 1;
}
}
tmp += to_string(count) + res[res.size()-1];
res = tmp;
}
return res;
}
};
前一篇文章:T65-括号生成
给我好看
本文分享自微信公众号 - 木又AI帮(gh_eaa31cab4b91)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。