• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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.

一次过, 注意29-31行的结尾处理,不要忘记

 1 public class Solution {
 2     public String countAndSay(int n) {
 3         if (n <= 0) return "";
 4         int i = 1;
 5         String current = "1";
 6         while (i < n){
 7             current = getnext(current);
 8             i++;
 9         }
10         return current;
11     }
12     
13     public String getnext(String current){
14         int j = 0, count = 0;
15         char st = current.charAt(0);
16         StringBuffer result = new StringBuffer();
17         while (j < current.length()){
18             if (current.charAt(j) == st){
19                 count++;
20                 j++;
21             } else{
22                 result.append(count);
23                 result.append(st);
24                 st = current.charAt(j);
25                 count = 1;
26                 j++;
27             }
28         }
29         result.append(count);
30         result.append(st);
31         return result.toString();
32     }
33 }

 

posted @ 2014-05-13 12:30  neverlandly  阅读(286)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3