搜索此博客

2012年9月11日星期二

Count And Say


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.

This question is a typical DP problem. The nth sequence can be calculated from the (n-1)th sequence. Therefore, we just store the result of each step.

public String countAndSay(int n) {
   String []sequence=new String[n];
   sequence[0]="1";
 
   for(int i=1;i<n;i++)
   {
       char[] str=sequence[i-1].toCharArray();
       StringBuffer sb=new StringBuffer();
       int start_value=str[0]-'0';
       int j=1;
       int counter=1;
       while(j<str.length)
       {
           if(str[j]-'0'==start_value)
           {
               counter++;
           }
           else
           {
               sb.append(counter);
               sb.append(start_value);
               start_value=str[j]-'0';
               counter=1;
           }
           j++;
       }
       sb.append(counter);
       sb.append(start_value);
       sequence[i]=sb.toString();
   }
 
   return sequence[n-1];
}

没有评论:

发表评论