38. Count and Say
Leetcode
https://leetcode.com/problems/count-and-say/
題目
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"countAndSay(n)is the way you would "say" the digit string fromcountAndSay(n-1), which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.
For example, the saying and conversion for digit string "3322251":

Given a positive integer n, return the nth term of the count-and-say sequence.
解答
方法一
遞迴計算
var countAndSay = function(n) {
if(n===1) return '1';
const str = countAndSay(n-1);
let output = '';
let count = 1;
for(let i=0; i<str.length; i++) {
if(str[i+1] === str[i]) count++;
else {
output += count.toString() + str[i];
count = 1;
}
}
return output;
};Runtime: 72 ms, faster than 90.82% of JavaScript online submissions for Count and Say.
Memory Usage: 42 MB, less than 16.50% of JavaScript online submissions for Count and Say.
測資
console.log(countAndSay(5))參考資料
Last updated
Was this helpful?