您的位置:首页 > 编程语言 > Java开发

Leetcode:38. Count and Say(JAVA)

2016-03-15 19:49 519 查看
【问题描述】

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到n循环,内层依次扫描上一层数字。

【code】

public class Solution {
public String countAndSay(int n) {
if (n < 0) {
return null;
}
String result = "1";
StringBuffer sb = null;
if (n == 1) {
return result;
} else {
for (int i = 2; i <= n; i++) {
sb = new StringBuffer();
int count = 0;
char c = result.charAt(0);
for (int j = 0; j < result.length(); j++) {
if (result.charAt(j) == c) {
count++;
} else {
sb.append(count);
sb.append(c);
c = result.charAt(j);
count = 1;
}
}
sb.append(count);
sb.append(c);
result = sb.toString();
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode