zoukankan      html  css  js  c++  java
  • leetcode------Count and Say

    标题: Count and Say
    通过率: 25.8%
    难度: 简单

    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.

    我感觉这个题目没有描述清楚,看了白天,查了半天我才明白,他给的例子应该到第六个这样就清楚了。

    n=1时,由于没有n=0  输出1;

    n=2时,看n=1,只有一个1所以输出11,意思就是一个1

    n=3时,看n=2,两个1所以输出21,意思就是两个1,

    一次类推。

    根据n数量去更新字符串就行了,从位置1开始每次比较前一个位置的元素,相同则计数器叠加,不同则存入。字符串又支持覆盖操作,比数组操作简单多了。直接看代码:

     1 public class Solution {
     2 public String countAndSay(int n) {
     3     if(n==1)return "1";
     4     String result="1";
     5     int count=1,level=1;
     6     while(level<n){
     7         StringBuffer tmp=new StringBuffer();
     8         count=1;
     9         for(int i=1;i<result.length();i++){
    10             if(result.charAt(i)==result.charAt(i-1))count++;
    11             else{
    12                 tmp.append(count);
    13                 tmp.append(result.charAt(i-1));
    14                 count=1;
    15             }
    16         }
    17         tmp.append(count);
    18         tmp.append(result.charAt(result.length()-1));
    19         result=tmp.toString();
    20         level++;
    21     }
    22     return result;
    23 }
    24 }
  • 相关阅读:
    阿里打败腾讯的步骤
    开发自己的工作流(一)
    基础理解5:引导图
    基础理解4:弹出层和拖动
    基础理解:3作用域作用域链
    基础理解2:CSS3按钮动画
    基础理解1:JSONP
    Cordova中使用gulp
    关于SharePoint 2013的工作流(二)
    关于SharePoint 2013的工作流(一)
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4253520.html
Copyright © 2011-2022 走看看