版权声明:文章都是原创,转载请注明~~~~ https://blog.csdn.net/SourDumplings/article/details/86529156
Easy
6254420FavoriteShare
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
C++:
/*
@Date : 2019-01-17 10:37:27
@Author : 酸饺子 ([email protected])
@Link : https://github.com/SourDumplings
@Version : $Id$
*/
/*
https://leetcode.com/problems/count-and-say/
*/
class Solution
{
public:
string countAndSay(int n)
{
string res = "";
for (int i = 0; i < n; ++i)
{
doCountAndSay(res);
}
return res;
}
void doCountAndSay(string &res)
{
if (res.empty())
{
res = "1";
return;
}
char lastD = res[0];
int lastCount = 1;
string newRes = "";
for (int i = 1; i < res.length(); ++i)
{
if (res[i] == lastD)
{
++lastCount;
}
else
{
newRes += to_string(lastCount) + lastD;
lastCount = 1;
lastD = res[i];
}
}
newRes += to_string(lastCount) + lastD;
res = move(newRes);
return;
}
};
Java:
/**
* @Date : 2019-01-17 11:12:58
* @Author : 酸饺子 ([email protected])
* @Link : https://github.com/SourDumplings
* @Version : $Id$
*
* https://leetcode.com/problems/count-and-say/
*/
class Solution
{
String res = "";
public String countAndSay(int n)
{
for (int i = 0; i != n; ++i)
{
doCountAndSay();
}
return res;
}
void doCountAndSay()
{
if (res.length() == 0)
{
res = "1";
return;
}
char lastD = res.charAt(0);
int lastCount = 1;
String newRes = "";
for (int i = 1; i < res.length(); ++i)
{
if (res.charAt(i) == lastD)
{
++lastCount;
}
else
{
newRes += Integer.toString(lastCount) + Character.toString(lastD);
lastD = res.charAt(i);
lastCount = 1;
}
}
newRes += Integer.toString(lastCount) + Character.toString(lastD);
res = newRes;
return;
}
}