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

LeetCode : Count and Say [java]

2016-03-11 22:09 441 查看
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.

思路:递归生成字符串,注意字符转字符串需要用String.valueOf()方法。

public class Solution {

public String countAndSay(int n) {
String str = "1";
for (int i = 1; i < n; i++) {
str = solve(str);
}
return str;
}

public String solve(String str) {
String result = "";
char ch = str.charAt(0);
System.out.println(ch);
int count = 1;
for (int i = 1; i < str.length(); i++) {
char c = str.charAt(i);
if (ch == c) {
count++;
} else {
char t = (char) (count + '0');
result += String.valueOf(t) + String.valueOf(ch);
ch = c;
count = 1;
}
}
char t = (char) (count + '0');
result += String.valueOf(t) + String.valueOf(ch);
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: