標籤: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