报数
题目
报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, …
1 读作 “one 1” -> 11.
11 读作 “two 1s” -> 21.
21 读作 “one 2, then one 1” -> 1211.
给定一个整数 n, 返回 第 n 个顺序。注意事项
整数的顺序将表示为一个字符串。样例
给定 n = 5, 返回 “111221”.
题解
本题主要难点在于读懂题意,意思是要求我们对字符串中连续相同的子串进行翻译,如:
1,表示只有1个1,则->11;
11,连续子串为11,表示有2个1,则->21;
21,连续子串为2和1,表示有1个2和1个1,则->1211;
1211,连续子串为1个1,1个2,2个1,表示有1个1、1个2,2个1,则->111221;
……
理解了题意,代码就很简单了,对原始字符串进行遍历,找出连续子串,并用子串的“长度+字符”表示即可。
public class Solution {
/**
* @param n the nth
* @return the nth sequence
*/
public String countAndSay(int n) {
String oldString = "1";
while (--n > 0)
{
StringBuilder sb = new StringBuilder();
char [] oldChars = oldString.toCharArray();
for (int i = 0; i < oldChars.length; i++)
{
int count = 1;
while ((i+1) < oldChars.length && oldChars[i] == oldChars[i+1])
{
count++;
i++;
}
sb.append(String.valueOf(count) + String.valueOf(oldChars[i]));
}
oldString = sb.toString();
}
return oldString;
}
}
Last Update 2016.9.16