题目为报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
-
1
-
11
-
21
-
1211
-
111221
1 被读作 “one 1” (“一个一”) , 即 11。
11 被读作 “two 1s” (“两个一”), 即 21。
21 被读作 “one 2”, “one 1” (“一个二” , “一个一”) , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
示例 1:
输入: 1
输出: “1”
示例 2:
输入: 4
输出: “1211”
解题思路,首先要理解题目的意思,
- 1=>11的 意思是 一个1
- 11=>21的意思是两个1
- 21=>1211的意思是 一个2 两个1
依次排序 我给出的代码代码为
public static string CountAndSay(int n)
{
string res = "1";
if (n==1)
{
return res;
}
for (int i = 1; i < n; i++)
{
int Count = 0;//计算单个字母总数
Stack st = new Stack();//记录当前字母
StringBuilder sb = new StringBuilder();
for (int j = 0; j < res.Length; j++)
{
if (j==0)
{
st.Push(res[0]);
Count += 1;
}
else if ((char)st.Peek()==res[j])
{
Count += 1;
}
else
{
sb.Append(Count == 0 ? "1" : Count.ToString() + st.Pop());
st.Push(res[j]);
Count = 1;
}
if (j==res.Length-1)
{
sb.Append(Count == 0 ? "1" : Count.ToString() + st.Pop());
}
}
res = sb.ToString();
}
return res;
}