zoukankan      html  css  js  c++  java
  • 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.

    Note: The sequence of integers will be represented as a string.

     1 public class Solution {
     2     public String countAndSay(int n) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         String say = "1";
     6         for(int i = 1; i < n; i++){
     7             say = cas(say);
     8         }
     9         
    10         return say;
    11     }
    12     
    13     public String cas(String say){
    14         int len = say.length();
    15         int last = 0;
    16         String tmp = "";
    17         for(int i = 0; i < len; i++){
    18             if(say.charAt(i) != say.charAt(last)){
    19                 tmp = tmp + (i - last) + say.charAt(last);
    20                 last = i;
    21             }
    22         }
    23         if(last < len){
    24             tmp = tmp + (len - last) + say.charAt(last);
    25         }
    26         
    27         return tmp;
    28     }
    29 }

    Just simulate the process until find the the n-th string, note the description it self is a bit fuzzy, count means you count the consecutive number, it is not true that there is only 1 or 2 in the string, so 1, 11, 21, 1211, 111221, the next would be 312211 because there are 3 consecutive 1 followed by 2 consecutive 2 and a single 1.

    http://tech-wonderland.net/blog/leetcode-count-and-say.html

  • 相关阅读:
    python 获取时间戳
    【转载】Git分支
    【转载】Jmeter分布式测试
    【总结】异常处理
    【转载】linux-查看日志
    【转载】python中if-else的多种写法
    【转载】Linux中rz和sz命令
    【转载】pip 使用国内源
    wrk(一)
    angular-gridster2使用
  • 原文地址:https://www.cnblogs.com/feiling/p/3234041.html
Copyright © 2011-2022 走看看