leetcode-38 Count and Say
2015-05-04 17:00
381 查看
开始没看懂题目,查了一下……囧。
思路很清晰,自己写的程序经过修改精简后,如下:
leetcode 显示时间为6ms.
教训:由于某些变量的定义地方选择不当,导致逻辑错误,很难检测出来,以后要小心小心再小小心!
然后在网上浏览,发现了高人写的更加优秀的程序,学习之后,佩服不已,故粘贴过来,仅供学习之用,在此感谢作者高人的分享。
地址:
/article/5002331.html
这段程序跑了一下,leetcode时间为3ms!!
佩服得五体投地!
思路非常清晰,操作非常简单,效率非常之高!
由于自己还是菜鸟,第一次见识到stringstream的厉害,心中佩服。
路漫漫其修远兮……哎
思路很清晰,自己写的程序经过修改精简后,如下:
class Solution { public: string countAndSay( int n){ if( n <= 0)//排除不符合条件的n return "";//输出为空 string say = "1";//用于保存结果,初始化为“1” for( int i = 1; i < n; ++i)//输入有效时,总的循环框架 { string tmp;//存储每次循环的中间结果 int count = 0;//计算每个数字出现的次数 char last = say[0];//作为参照的数 //每个子循环的次数为当前数的字符串长度 for( size_t j=0; j <= say.size(); ++j) { if(say[j] == last)//如果数字相同 ++count;//计数加一 else//数字不同 { char num = '0' + count;//计算当前数字出现次数 tmp = tmp + num + last;//将次数与数字存入中间变量 last = say[j];//将参照的数改变(可看做在数组中向前移动) count = 1;//将计数置为1 } } say = tmp;//将一次子循环结束的结果赋给say,判断条件,若可,继续循环,若不可,结束循环 } return say;//返回结果 } };
leetcode 显示时间为6ms.
教训:由于某些变量的定义地方选择不当,导致逻辑错误,很难检测出来,以后要小心小心再小小心!
然后在网上浏览,发现了高人写的更加优秀的程序,学习之后,佩服不已,故粘贴过来,仅供学习之用,在此感谢作者高人的分享。
地址:
/article/5002331.html
class Solution { public: string ungarded_convert( const string &say ) { stringstream ss; int count = 0; char last = say[0]; for( size_t i=0; i <= say.size(); ++i ) { if(say[i] == last ) ++count; else { ss << count << last; count = 1; last = say[i]; } } return ss.str(); } string countAndSay(int n) { if( n <= 0) return string(); string say = "1"; for(int i=1; i < n; ++i) { say = ungarded_convert( say ); } return say; } };
这段程序跑了一下,leetcode时间为3ms!!
佩服得五体投地!
思路非常清晰,操作非常简单,效率非常之高!
由于自己还是菜鸟,第一次见识到stringstream的厉害,心中佩服。
路漫漫其修远兮……哎
相关文章推荐
- 【LeetCode 38】Count and Say(Python)
- Leetcode 38 Count and Say
- 【LeetCode】C# 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
- Leetcode38:count and say数一数,说一说
- [LeetCode 38] Count and Say
- leetcode 38 Count and Say
- Leetcode 38,Count and say
- Leetcode 38 Count and Say
- LeetCode38 - Count and Say
- leetcode——38——Count and Say
- LeetCode 38:Count and Say
- leetcode 38:Count and Say
- LeetCode-38-Count and Say Python的int_to_string