标签:
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.
这道题其实不是很难,关键是要耐心,每一个后面的数字都是根据前面的数字推算出来的,用一个for循环来数重复的数字的个数,
1 package Count.and.Say; 2 3 public class CountAndSay { 4 public String countAndSay(int n) { 5 if(n==1){ 6 return "1"; 7 } 8 String curr="1"; 9 for(int i=1;i<n;i++){ 10 int size=curr.length(); 11 int currIndi=0; 12 StringBuilder tempBuilder=new StringBuilder(); 13 while(currIndi<size){ 14 int count=1; 15 int k=currIndi+1; 16 while(k<size&&curr.charAt(k-1)==curr.charAt(k)) 17 { 18 count++; 19 k++; 20 } 21 tempBuilder.append(count).append(curr.charAt(currIndi)); 22 currIndi=k; 23 } 24 curr=tempBuilder.toString(); 25 } 26 return curr.toString(); 27 } 28 public static void main(String []args){ 29 CountAndSay service=new CountAndSay(); 30 String s=service.countAndSay(6); 31 System.out.println(s); 32 } 33 }
标签:
原文地址:http://www.cnblogs.com/criseRabbit/p/4302324.html