[LeetCode][Java] Count and Say

來源:互聯網
上載者:User

標籤:leetcode   java   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.

題意:

count-and-say 序列是如下面所示的一組整數數列:
1, 11, 21, 1211, 111221, ...

1 讀作“一個1”或者11.

11讀作"兩個1" 或者 21.

21讀作“一個2”,和“一個1” 或者 1211.

給定一個整數 n,產生第n個序列。

注意:這個產生的整數序列應該用一個字串表示出來。

演算法分析:

    * 題目說的實在是太不明白了。。。
    
    * 解釋一下就是,輸入n,那麼我就打出第n行的字串。
    
    * 怎麼確定第n行字串呢?他的這個是有規律的。
    
    * n = 1時,列印一個1。
    
    * n = 2時,看n=1那一行,念:1個1,所以列印:11。
    
    * n = 3時,看n=2那一行,念:2個1,所以列印:21。
    
    * n = 4時,看n=3那一行,念:一個2一個1,所以列印:1211。
    
    * 以此類推。(注意這裡n是從1開始的)

    題目不難,直接上代碼

AC代碼:

public class Solution {    public  String countAndSay(int n)    {    String subres = "";    if (n==1) return "1";    int sn = 2;    String subinput="1";    while(sn<=n)    {    subres=SubsountandSay(subinput);    subinput=subres;    sn++;    }    return subres;        }private  String SubsountandSay(String n) {String res = "";    String oristring= n;    char tem;    int i = 0;    int startindex=0;    int k=0;    while(i<oristring.length())    {    k=0;    tem='\0';    while(i<oristring.length())    {    if(oristring.charAt(startindex)==oristring.charAt(i))    {    k++;    tem=oristring.charAt(i);    i++;    }    else    {    startindex=i;    break;    }    }    res+=Integer.toString(k)+tem;    }    return res;  }}



著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Count and Say

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.