[leetcode]Count and Say

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实现了一遍,其实感觉木有必要,迭代已经很简单了。

迭代算法如下:

 1 public class Solution {
 2     public String countAndSay(int n) {
 3         if (n <= 0) {
 4             return null;
 5         }
 6         String s = "1";
 7         int num = 1;
 8         for (int j = 0; j < n - 1; j++) {
 9             StringBuilder sb = new StringBuilder();
10             for (int i = 0; i < s.length(); i++) {
11                 if (i < s.length() - 1 && s.charAt(i) == s.charAt(i + 1)) {
12                     num++;
13                 } else {
14                     sb.append(num + "" + s.charAt(i));
15                     num = 1;
16                 }
17             }
18             s = sb.toString();
19         }
20         return s;
21     }
22 }

递归实现如下:

 1 public class Solution {
 2     public String countAndSay(int n) {
 3         if(n <= 0) return "";
 4         if(n == 1) return "1";
 5         String pre = countAndSay(n - 1);
 6         int length = pre.length();
 7         int from = 0, to = 0;
 8         StringBuilder sb = new StringBuilder();
 9         while(to < length){
10             while(to + 1< length && pre.charAt(to) == pre.charAt(to + 1)) to++;
11             sb.append(to - from + 1).append(pre.charAt(from));
12             from = to + 1;
13             to = from;
14         }
15         return sb.toString();
16     }
17 }

 

 

dfs算法如下:

 1 public class Solution {
 2     String s = "1";
 3     public String countAndSay(int n) {
 4         if(n < 1) return "";
 5         for (int i = 1; i < n; i++)
 6             dfs(s.length());
 7         return s;
 8     }
 9 
10     private void dfs(int length) {
11         if (length == 0) return;
12         int count = 1, i = 0;
13         while (i < length - 1 && s.charAt(i) == s.charAt(1 + i)) {
14             count++;
15             i++;
16         }
17         s = s.substring(i + 1) + count + s.charAt(i);
18         dfs(length - count);
19     }
20 }

posted on 2014-07-16 20:42  喵星人与汪星人  阅读(395)  评论(0编辑  收藏  举报