38.[Leetcode]Count and Say
来源:互联网 发布:linux查看根目录命令 编辑:程序博客网 时间:2024/05/01 22:40
这道题倒是不难,但是我debug了好久,总有一些小问题。debug的效率也是效率之一,提高debug的能力,以后在做题的时候,给自己规定debug的时间
public class Solution { public String countAndSay(int n) { if(n == 0 || n == 1) return "1"; StringBuilder str = new StringBuilder("1"); StringBuilder newStr = new StringBuilder(""); int count = 1; for(int j=0;j<n-1;j++){ for(int i=0;i<str.length();i++){ if(!isEN(i,str)){ newStr.append(String.valueOf(count)); count = 1; newStr.append(str.charAt(i)); } else { count++; } } str = new StringBuilder(newStr.toString()); newStr = new StringBuilder(""); } return str.toString(); } public boolean isEN(int i,StringBuilder str){ if(i+1 == str.length() || str.charAt(i) != str.charAt(i+1)) return false; return true; }}
但是逻辑更优的则是 递归的方法,这简直是典型的递归问题
string countAndSay(int n) { if (n == 1) { return string("1"); } string prev = countAndSay(n-1); int before = 0; int count = 0; string curr; for (int i = 0; i < prev.length(); ++i) { if (prev[i]-'0' == before) { count++; continue; } else if (before != 0) { curr.append(1, '0' + count); curr.append(1, '0' + before); } before = prev[i]-'0'; count = 1; } if (before != 0 && count != 0) { curr.append(1, '0' + count); curr.append(1, '0' + before); } return curr;}
0 0
- [LeetCode]38.Count and Say
- LeetCode --- 38. Count and Say
- LeetCode 38.Count and Say
- [Leetcode] 38. Count and Say
- 38. Count and Say LeetCode
- Leetcode 38. Count and Say
- leetcode 38. Count and Say
- [leetcode] 38. Count and Say
- LeetCode-38.Count and Say
- LeetCode *** 38. Count and Say
- leetcode 38. Count and Say
- LeetCode-38. Count and Say
- LeetCode 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode - 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode 38. Count and Say
- LeetCode 38. Count and Say
- C++11 标准中char的注意事项
- 中英文识别+数字和定值
- 通过JDBC进行简单的增删改查(以MySQL为例)
- Wireshark学习四:网络性能排查之TCP重传与重复ACK
- (深搜)UVA - 1600 Patrol Robot
- 38.[Leetcode]Count and Say
- Wireshark学习五:TCP窗口与拥塞处理
- 混合编程中的export 、import和extern
- redis集群通过redis-cli -c
- 欢迎使用CSDN-markdown编辑器
- Wireshark学习六:狙击网络高延时点
- 单例模式
- Android连连看 -- 银魂连连看
- HDU 3666 THE MATRIX PROBLEM(差分约束)