38. Count and Say
Easy
6694834FavoriteShare
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"
不是说好的easy吗,为什么我调试了这么久,还放到VS里了。
class Solution {
public:
string countAndSay(int n) {
if(n == 1)return "1";
string ans = "";
int calnum = 0;
string a = "1";
while (n - 1 > 0)
{
ans = "";
calnum = 0;
//for (int i = 0; i < a.length(); i++)
//{
int j = 0;
int p = 0;
char t = a[p];
char ts = a[j];
while (j < a.length())
{
if (a[j] == a[p])
{
calnum++;
j++;
if (j == a.length())
{
ans += t;
ans += to_string(calnum);
}
}
else
{
ans += t;
ans += to_string(calnum);
calnum = 0;
p = j;
t = a[p];
}
}
//}
a = ans;
n--;
}
string ans1;
for (int i = ans.length() - 1; i >= 0; i--)
{
ans1 += ans[i];
}
return ans1;
}
};