首页 > 其他 > 详细

[Leetcode]-- Count and Say

时间:2014-02-12 21:00:10      阅读:337      评论: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.

双指针,记录相同的出现的字符的个数 ;

bubuko.com,布布扣
 1 public class Solution {
 2     public String countAndSay(int n) {
 3      
 4        String say = "1";
 5        for(int i = 1; i < n ; i++){
 6            say = build(say);
 7        }
 8        return say;
 9     }
10     
11     public String build(String s){
12         int len = s.length();
13         int last = 0;
14         String temp = "";
15         for(int i = 0; i < len; i++){
16             if(s.charAt(last) != s.charAt(i)){
17                 temp = temp + (i-last)+s.charAt(last);
18                 last = i;
19             }
20         }
21         
22         if(last < len){
23             temp = temp + (len -last) + s.charAt(last);
24         }
25         
26         return temp;
27     }
28 }
bubuko.com,布布扣

[Leetcode]-- Count and Say

原文:http://www.cnblogs.com/RazerLu/p/3545735.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!