標籤:序列 計數 演算法 面試 java
【038-Count and Say(計數和表述)】
【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】
原題
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時輸出字串1;n=2時,數上次字串中的數值個數,因為上次字串有1個1,所以輸出11;n=3時,由於上次字元是11,有2個1,所以輸出21;n=4時,由於上次字串是21,有1個2和1個1,所以輸出1211。依次類推,寫個countAndSay(n)函數返回字串。
解題思路
第一種情況:n<0時返回null。
第二種情況:當n=1時,返回1
第三種情況:當n>1時,假設n-1返回的字串是s,對s的串進行處理理,對不同的數字進行分組比如112365477899,分成11,2,3,6,5,4,77,8,99。最有就2個1,1個2,1個3,1個6,1個5,一個4,2個7,1個8,2個9,就是211213161614271829,返回此結果。
代碼實現
演算法實作類別
public class Solution { public String countAndSay(int n) { if (n < 1) { return null; } String result = "1"; for (int i = 2; i <=n ; i++) { result = countAndSay(result); } return result; } public String countAndSay(String str) { StringBuilder builder = new StringBuilder(128); int count = 1; for (int i = 1; i < str.length(); i++) { if (str.charAt(i) == str.charAt(i - 1)) { count++; } else { builder.append(count); builder.append(str.charAt(i - 1)); count = 1; } } builder.append(count); builder.append(str.charAt(str.length() - 1)); return builder.toString(); }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47098327】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【LeetCode-面試演算法經典-Java實現】【038-Count and Say(計數和表述)】