您的位置:首页 > 其它

[leetcode]Count and Say

2014-07-16 20:42 183 查看
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. 扫描迭代,逐个处理,没啥难度。

2. 递归实现。

3. 这道题的难度表推荐算法是dfs,因此这一遍我用dfs实现了一遍,其实感觉木有必要,迭代已经很简单了。

迭代算法如下:

public class Solution {
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;
}
}


递归实现如下:

public class Solution {
public String countAndSay(int n) {
if(n <= 0) return "";
if(n == 1) return "1";
String pre = countAndSay(n - 1);
int length = pre.length();
int from = 0, to = 0;
StringBuilder sb = new StringBuilder();
while(to < length){
while(to + 1< length && pre.charAt(to) == pre.charAt(to + 1)) to++;
sb.append(to - from + 1).append(pre.charAt(from));
from = to + 1;
to = from;
}
return sb.toString();
}
}


dfs算法如下:

public class Solution {
String s = "1";
public String countAndSay(int n) {
if(n < 1) return "";
for (int i = 1; i < n; i++)
dfs(s.length());
return s;
}

private void dfs(int length) {
if (length == 0) return;
int count = 1, i = 0;
while (i < length - 1 && s.charAt(i) == s.charAt(1 + i)) {
count++;
i++;
}
s = s.substring(i + 1) + count + s.charAt(i);
dfs(length - count);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: