The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.
Note: The sequence of integers will be represented as a string.
简单递归,主要读懂题目。
n=1: ans = 1;
n=2: 读n=1的ans,即一个1,ans = 11;
n=3: 读n=2的ans,即两个1,ans = 21;
package leetcode;
public class CountandSay {
public String countAndSay(int n) {
String ans = "1";
int j = 1;
if (n == 1) return "1";
if (n >1){
while (j<n){
ans = revolution(ans);
j++;
}
}
return ans;
}
private String revolution(String frontStr) {
// TODO Auto-generated method stub
String ans = "";
int count = 1;
if (frontStr.length() == 1) {
ans = ans + count + frontStr;
return ans;
}
char[] chars = frontStr.toCharArray();
char frontChar = chars[0];
for (int i = 1; i<chars.length; i++){
if (frontChar == chars[i]){
count++;
}else{
ans = ans + count + frontChar;
count = 1;
frontChar = chars[i];
}
}
ans = ans + count + frontChar;
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new CountandSay().countAndSay(6));
}
}