原题链接:http://oj.leetcode.com/problems/count-and-say/这道题属于字符串操作的类型,算法上提高空间不大,只能是对于某一个数的串,读过去然后得到计数并生成下一个串。时间复杂度是O(n*串的长度),空间复杂度是O(串的长度)。代码如下:
public String countAndSay(int n) {
if(n<=0)
return "";
String curRes = "1";
for(int i=2;i<=n;i++)
{
StringBuilder res = new StringBuilder();
int count = 1;
for(int j=1;j<curRes.length();j++)
{
if(curRes.charAt(j)==curRes.charAt(j-1))
count++;
else
{
res.append(count);
res.append(curRes.charAt(j-1));
count = 1;
}
}
res.append(count);
res.append(curRes.charAt(curRes.length()-1));
curRes = res.toString();
}
return curRes;
}
小陷阱就是跑完循环之后记得把最后一个字符也加上,因为之前只是计数而已。这道题属于字符串或者说数组操作的类型,考察对于明确问题和算法的实现能力,一般会在电面,或者最容易的第一道题中出现,力求一遍搞定,不留bug哈。
分享到:
相关推荐
Leetcode原题Count and Say count-and-say序列是整数序列,前五个术语如下: 1. 1 2. 11 3. 21 1211 5. 111221 1被读作“1”或11。 11被读作“两个1”或21。 21被读作“一个2,然后一个1”或1211。 给定整数n,...
1_count_and_say.cpp - super_ugly_number.cpp - Detect_Pattern.cpp - degree_of_array.cpp - 键盘.cpp - 2Sum_Data_Structure_Design.cpp - shuffle_array.cpp - permutations.cpp - kth_missing_number.cpp - 3...
leetcode 答案LeetCode LeetCode in Swift 这个Repo 用来存下我在LeetCode ...Count and Say Easy #53 Maximum Subarray Easy #66 Plus One Easy #70 Climbing Stairs Easy #83 Remove Duplicates from Sorted L
leetcode卡 LeetCode LeetCode题解 目录 字符串问题 ID Title C++ 难度 备注 0008 String to Integer(atoi) ...Count and Say :star: 0043 Multiply Strings :star: :star: 大数相乘 0044 Wild Card Matchi
201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _...
leetcode中国 我自己的leetcode刷题记录 ###[20150920] ...count and say , easy , 模拟 Anagrams 字符串处理,map Simplify Path,字符串处理,stack Length of Last Word,字符串处理.细节题 Rever
leetcode给单链表加一js实现 LeetCode By JavaScript LeetCode Solutions (All By JavaScript!) 的个人Solutions汇总,全部使用JavaScript完成:grinning_squinting_face: 目的:了解、掌握数据结构和算法,当然...Say:
https://leetcode.com/problems/count-and-say/ 3, java/dungenegame https://leetcode.com/problems/dungeon-game/ 4, java/findminrotaed 5, java/houserobber https://leetcode.com/problems/house-robber/
Count_and_Say 循环n次依次计算即可,注意0次等边界情况 Longest_Consecutive_Sequence 双向确认是否连续,避免重复的n^2复杂度 Palindrome_Partitioning DP,避免递归调用,利用数组储存已算出来的数值,由后向前...
“count_n_say.py” - 使用迭代方法生成 Count 和 Say 序列的第 n 项。 “count_segments.py” - 该算法计算字符串中的段数,其中段被定义为连续的非空格字符序列。 "count_negatives_2d_array.py" - 给定一个二维...
3.12 Count and Say 3.13 变位词 3.14 简化系统路径 3.15 最后一个单词的长度 3.16 反转字符串中的单词 3.16.1 字符串前后和中间可能存在多个空格 3.16.2 不存在前后和中间的多余空格 3.17 一个编辑距离 4. 栈 4.1 ...
Practice-Leetcode 这是一个Chinese School Girl:China:用来练习leetcode的文档.每道下面的题都有详细的解题思路,和知识点分析,尽请参考。 找实习的小伙伴也可以参考我的Tech-blog...038.Count and Say 递归 040.C
Count and Say Anagrams Valid Anagram Simplify Path Length of Last Word Isomorphic Strings Word Pattern 栈和队列 栈 Min Stack Valid Parentheses Longest Valid Parentheses Largest Rectangle in Histogram ...