LeetCode 38 : Count and Say (Java)
来源:互联网 发布:编程工具与编程 编辑:程序博客网 时间:2024/05/22 13:33
解题思路:我表示这道题对我来说关键就是理解题意。。。真的没理解题意,网上查了才恍然大悟。首先说一下题意。n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。理解题意后,关键就是如何say一串数字了。 依次读入每个字符,对于每个字符,首先判断用于计数的count是否为0,如果不为0,表示前面该字符前面已经有字符了,所以再判断该字符和前一个字符是否相等,如果不相等,就把前面计算的结果添加到result中去,同时把count清零,最后count加1。
public class Solution { public String countAndSay(int n) { if(n == 1) { return 1+""; } String result = "1"; for(int i=2;i<=n;i++) { result = say(result); } return result; } public String say(String s) { String result = ""; int count = 0; char c = '0'; for(int i=0;i<s.length();i++) { c = s.charAt(i); if(count !=0) { if(s.charAt(i-1) != c) { result = result + count + s.charAt(i-1); count = 0; } } count++; } result = result + count + c; return result; }}
0 0
- [leetcode-38]count and say(java)
- LeetCode 38 : Count and Say (Java)
- [Leetcode] Count and Say (Java)
- [LeetCode][Java] Count and Say
- count and say leetcode java
- LeetCode : Count and Say [java]
- LeetCode Count and Say(java)
- [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
- zjnu(1299)——零件分组(LIS变形)
- Android Studio使用心得
- JAVA_SE ----- 基础知识总结-----关键字,标识符,注释,常量
- printf_系统调用过程分析_write() putc() 函数实现
- 学自慕课网:Dom对象控制Html元素(二)
- LeetCode 38 : Count and Say (Java)
- 多线程编程-线程的创建和终止
- 什么是性能测试?
- 一步一步教你Socket编程
- 初识RMAN2:12C中数据文件和归档日志的保留策略
- 自定义控件-侧拉菜单
- 华为的模式
- Oracle ROWID详解
- UI基础-XML、JSON 数据结构解析