LeetCode --- 字符串、數(shù)組
簡(jiǎn)書(shū)專(zhuān)欄:http://www.itdecent.cn/nb/41796568
知乎專(zhuān)欄:https://zhuanlan.zhihu.com/c_174823416
一、題目描述
來(lái)源:力扣(LeetCode)
「外觀數(shù)列」是一個(gè)整數(shù)序列,從數(shù)字 1 開(kāi)始,序列中的每一項(xiàng)都是對(duì)前一項(xiàng)的描述。前五項(xiàng)如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 被讀作 "one 1" ("一個(gè)一") , 即 11。
11 被讀作 "two 1s" ("兩個(gè)一"), 即 21。
21 被讀作 "one 2", "one 1" ("一個(gè)二" , "一個(gè)一") , 即 1211。
給定一個(gè)正整數(shù) n(1 ≤ n ≤ 30),輸出外觀數(shù)列的第 n 項(xiàng)。
注意:整數(shù)序列中的每一項(xiàng)將表示為一個(gè)字符串。
要求實(shí)現(xiàn)函數(shù):
public String countAndSay(int n) {}
二、實(shí)現(xiàn)思路以及代碼
本題首先要理解題目的含義。第1個(gè)數(shù)為1,讀作一個(gè)一,所以第二個(gè)數(shù)為11,讀作二個(gè)一,所以第三個(gè)數(shù)21,依次類(lèi)推,可以看出是一種遞推的關(guān)系,后一個(gè)數(shù)是對(duì)前一個(gè)數(shù)的描述?;谠撍枷雭?lái)依次推出第N個(gè)值,遍歷當(dāng)前字符串,依次讀出該字符串,定義變量count記錄重復(fù)數(shù)字的個(gè)數(shù),當(dāng)遇到不相等字符時(shí),將count重置為1,已讀部分加入字符串中即可。
實(shí)現(xiàn)代碼:
public static String countAndSay(int n) {
if(n <= 0) {
return "";
}
String[] strs = new String[n];
strs[0] = "1";
for(int i = 1; i < n; i++) {
strs[i] = convert(strs[i-1]);
}
return strs[n - 1];
}
//讀出該字符串
public static String convert(String str) {
StringBuffer br = new StringBuffer();
int count = 1;
for(int i = 0; i < str.length(); i++) {
if ((i < str.length() - 1) && (str.charAt(i) == str.charAt(i + 1))) {
count++;
} else {
br.append(count).append(str.charAt(i));
count = 1;
}
}
return br.toString();
}
三、測(cè)試代碼
public static void main(String[] args) {
for (int i = 1; i < 7; i++) {
System.out.println(countAndSay(i));
}
}
輸出結(jié)果為:
1
11
21
1211
111221
312211