leetcode -- 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.

 

 1 public class Solution {
 2     public String countAndSay(int n) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         String say = "1";
 6         for(int i = 1; i < n; i++){
 7             say = cas(say);
 8         }
 9         
10         return say;
11     }
12     
13     public String cas(String say){
14         int len = say.length();
15         int last = 0;
16         String tmp = "";
17         for(int i = 0; i < len; i++){
18             if(say.charAt(i) != say.charAt(last)){
19                 tmp = tmp + (i - last) + say.charAt(last);
20                 last = i;
21             }
22         }
23         if(last < len){
24             tmp = tmp + (len - last) + say.charAt(last);
25         }
26         
27         return tmp;
28     }
29 }

 

Just simulate the process until find the the n-th string, note the description it self is a bit fuzzy, count means you count the consecutive number, it is not true that there is only 1 or 2 in the string, so 1, 11, 21, 1211, 111221, the next would be 312211 because there are 3 consecutive 1 followed by 2 consecutive 2 and a single 1.

http://tech-wonderland.net/blog/leetcode-count-and-say.html

posted @ 2013-08-02 23:56  feiling  阅读(428)  评论(0编辑  收藏  举报