Skip to content

38. Count and Say / Medium / JavaScript #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions yeongrok/0038-count-and-say/0038-count-and-say.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @param {number} n
* @return {string}
*/
var countAndSay = function(n) {
if (n === 1) return "1";

const digitStrings = countAndSay(n-1);
let accStr = "";

for (let i = 0; i < digitStrings.length; i++) {
let count = 1;
while (i + 1 < digitStrings.length && digitStrings[i] === digitStrings[i + 1]) {
count++;
i++;
}
accStr += `${count}${digitStrings[i]}`;
}
return accStr;
};
40 changes: 40 additions & 0 deletions yeongrok/0038-count-and-say/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<h2><a href="https://leetcode.com/problems/count-and-say/">38. Count and Say</a></h2><h3>Medium</h3><hr>Can you solve this real interview question? 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 from countAndSay(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 substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.

For example, the saying and conversion for digit string "3322251":

[https://assets.leetcode.com/uploads/2020/10/23/countandsay.jpg]

Given a positive integer n, return the nth term of the count-and-say sequence.



Example 1:


Input: n = 1
Output: "1"
Explanation: This is the base case.


Example 2:


Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"




Constraints:

* 1 <= n <= 30