首页 > 其他 > 详细

Leetcode Count and Say

时间:2015-02-27 00:07:13      阅读:330      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!