[LeetCode] Count and Say 数数并说
2018-02-27 10:32
295 查看
数数并说序列是一个整数序列,第二项起每一项的值为对前一项的计数,其前五项如下:
1
11
21
1211
111221
1 被读作 “一个一” 即 11。
11 被读作 “两个一” 即 21。
21 被读作 “一个二 和 一个一” 即 1211。
给一个正整数 n ,输出数数并说序列的第 n 项。
注意:该整数序列的每项都输出为字符串。
例 1:
例 2:
思路:对于前一个数,找出相同元素的个数,把个数和该元素存到新的string里。
1
11
21
1211
111221
1 被读作 “一个一” 即 11。
11 被读作 “两个一” 即 21。
21 被读作 “一个二 和 一个一” 即 1211。
给一个正整数 n ,输出数数并说序列的第 n 项。
注意:该整数序列的每项都输出为字符串。
例 1:
输入: 1 输出: "1"
例 2:
输入: 4 输出: "1211"
思路:对于前一个数,找出相同元素的个数,把个数和该元素存到新的string里。
/** * @param {number} n * @return {string} */ var countAndSay = function(n) { if (n <= 0) return ""; let res = "1"; while (--n) { let cur = ""; for (let i = 0; i < res.length; ++i) { let cnt = 1; while (i + 1 < res.length && res[i] == res[i + 1]) { ++cnt; ++i; } cur += cnt.toString() + res[i]; } res = cur; } return res; };
相关文章推荐
- [LeetCode]Count and Say
- LeetCode 038 Count and Say
- [LeetCode] Count and Say
- [LeetCode] Count and Say 计数和读法
- leetcode记录——Count and Say
- LeetCode 38 Count and Say(字符串规律输出)
- [leetcode] Count and Say
- 【leetcode】Count and Say
- 【leetcode】Count and Say (easy)
- LeetCode: Count and Say
- LeetCode --- Count And Say
- LeetCode题解——Count and Say
- leetcode 38:count and say
- LEETCODE: Count and Say
- [Leetcode] Count and Say
- LeetCode 37 Count and Say
- 【C++】数数:用数字来数数Count and Say
- leetcode_38题——Count and Say(string,迭代计数)
- leetcode: Count and Say
- [LeetCode]38 Count and Say