一、Description:
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, 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"
二、Ideas:
1.题意解读:
本题目的是实现数字的口语化转换,例如:当字符串为“1”时,读作“1个1”,所以需要转换成:“11”;同样,“11”读作“2个1”,所以需要转换成“21”;那么,“21”则被读作“1个2,1个1”,即“1211”,以此类推,找到第n个字符串。
2.思路:
在了解题意后,本题的思路就比较简单了。首先,给定一个初始字符串“1”,然后,根据给定的n遍历,每次遍历都需要从头遍历当前字符串,检查相同字符的个数,并设定一个mark,用于标记一次计数的结束,只有计数结束才可以更新字符串,这里需要注意两个临界条件:1.最后一个字符和前一个字符相同,这时,由于计数并没有结束,但显然下一次就结束遍历了,所以需要人为将计数结束并更新字符串;2.最后一个字符和前一个字符不相同,此时由于上一次计数已经结束,字符串已经更新,但显然这之后就会退出遍历了,所以需要将最后一个字符更新到字符串里。
三、Code:
class Solution {
public String countAndSay(int n) {
String str="1";
for(int i=1;i<n;i++){
int len=str.length();
int num=1;
int mark=0;
String mid=new String();
if(len==1) {
mid="1"+String.valueOf(str.charAt(0));
}
for(int j=0;j+1<len;j++){
if(str.charAt(j)==str.charAt(j+1)){
num++;
mark=0;
}
else mark=1;
if(mark==1){
mid=mid+String.valueOf(num)+String.valueOf(str.charAt(j));
if(j+1==len-1) mid=mid+"1"+String.valueOf(str.charAt(j+1));
num=1;
}
else if(j+1==len-1){
mid=mid+String.valueOf(num)+String.valueOf(str.charAt(j));
num=1;
}
}
str=mid;
}
return str;
}
}