首页 > 代码库 > [leetcode]Count and Say
[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. 这道题的难度表推荐算法是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 }
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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。