新博文地址:[leetcode]Count and Say
第二遍使用了dfs算法,代码相对稍稍简洁了一丢丢,基本差不多,思想也相仿
http://oj.leetcode.com/problems/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.
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.
这道题目相对比较容易,也不牵扯什么算法。只需要扫描字符串,计数,输出,即可。
比如我们再扫描1211的时候,看1后面是2,则1的count = 1,则将count + 1写入字符串中,2也一样,2后面的1,1后面还是1,则count++,第二个1后面没有了,则将count+1写入字符串,输入完毕。
因此打印的就是11+12+21即111221。
public String countAndSay(int n) {
if (n <= 0) {
return null;
}
String s = "1";
int num = 1;
for (int j = 0; j < n - 1; j++) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (i < s.length() - 1 && s.charAt(i) == s.charAt(i + 1)) {
num++;
} else {
sb.append(num + "" + s.charAt(i));
num = 1;
}
}
s = sb.toString();
}
return s;
}