数数并说序列是一个整数序列,第二项起每一项的值为对前一项的计数,其前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 被读作 "一个一" 即 11。
11 被读作 "两个一" 即 21。
21 被读作 "一个二 和 一个一" 即 1211。
给一个正整数 n ,输出数数并说序列的第 n 项。
注意:该整数序列的每项都输出为字符串。
例 1:
输入: 1
输出: "1"
例 2:
输入: 4
输出: "1211"
详见:https://leetcode.com/problems/count-and-say/description/
实现语言:Java
class Solution {
public String countAndSay(int n) {
if(n<=0){
return null;
}
String s="1";
for(int i=1;i<n;++i){
StringBuilder tmp=new StringBuilder();
int cnt=1;
for(int j=1;j<s.length();++j){
if(s.charAt(j)==s.charAt(j-1)){
++cnt;
}else{
tmp.append(cnt);
tmp.append(s.charAt(j-1));
cnt=1;
}
}
tmp.append(cnt);
tmp.append(s.charAt(s.length()-1));
s=tmp.toString();
}
return s;
}
}
实现语言:C++
class Solution {
public:
string countAndSay(int n) {
if(n<=0)
{
return nullptr;
}
string s="1";
for(int i=1;i<n;++i)
{
string tmp="";
int cnt=1;
for(int j=1;j<s.size();++j)
{
if(s[j]==s[j-1])
{
++cnt;
}
else
{
tmp=tmp+char(cnt+'0')+s[j-1];
cnt=1;
}
}
s=tmp+char(cnt+'0')+s[s.size()-1];
}
return s;
}
};