問題:
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, 11, 21, 1211, 111221, ...
1 被稱為 "一個1" 或者 11.
11 被稱為 "兩個1" 或者 21.
21 被稱為 "兩個2, 然后一個1" 或者 1211.
給出一個整型n,生成第n個序列。
注意:整型序列需要時字符串的形式。
思路:
乍一看題目沒懂意思,后來知道了,就是看上一個序列的數字,念出來是什么樣子就寫什么樣子,比如一個1,兩個2一個1,這么念的就這么寫。
做法的話其實只能循環著來老老實實做,只是在做的時候要注意一些邊界情況,最后輸出的是第n個序列,不是整體n個序列的連接,無非就是一個個算下來,判斷有幾個連續的什么數字,然后加進去,這里利用數組來做循環方便一些,最后再轉換成字符串。
有些要注意的是在做序列時由于循環的條件限制,每次序列的最后一段需要額外寫一下,而且數組的復制要使用clone的深度復制,否則只是淺復制,拿到一個引用而已,修改數組時兩個數組都會發生變化,代碼寫的比較丑,后面別人寫的要稍微好看一點,但是思路還是比較清晰地。
代碼(Java):
public class Solution {
public String countAndSay(int n) {
if (n == 0) return "";
int[] resultArray = new int[10000];
resultArray[0] = 1;
int index = 1;
for (int i = 1; i < n; i++) {
int last = resultArray[0];
int lastSame = 0;
int[] tempArray = new int[10000];
int num = 0;
int j = 0;
for (; j < index; j++) {
if (resultArray[j] == last) lastSame++;
else {
tempArray[num] = lastSame;
tempArray[num+1] = last;
last = resultArray[j];
lastSame = 1;
num += 2;
}
}
tempArray[num] = lastSame;
tempArray[num+1] = last;
num += 2;
index = num;
resultArray = tempArray.clone();
}
int[] trueArray = Arrays.copyOfRange(resultArray, 0, index);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < trueArray.length; i++) {
sb.append(trueArray[i]);
}
return sb.toString();
}
}
他山之石:
public class Solution {
public String countAndSay(int n) {
StringBuilder curr = new StringBuilder();
StringBuilder prev = new StringBuilder();
if(n<=0) return curr.toString();
curr.append(1);
for(int i = n; i>1; i--) {
prev = curr;
curr = new StringBuilder();
char[] c = prev.toString().toCharArray();
int count = 1;
for(int j = 1; j <=c.length; j++) {
if(j == c.length || c[j]!=c[j-1]) {
curr.append(count);
curr.append(c[j-1]);
count = 1 ;
} else {
count++;
}
}
}
return curr.toString();
}
}
合集:https://github.com/Cloudox/LeetCode-Record