码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Count and Say

时间:2015-02-27 00:08:56      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Leetcode Count and Say

标签:

原文地址:http://www.cnblogs.com/criseRabbit/p/4302324.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!