Skip to content

Commit dc86c06

Browse files
committedJan 5, 2023
Add solution #38
1 parent dbe025e commit dc86c06

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium|
4141
35|[Search Insert Position](./0035-search-insert-position.js)|Easy|
4242
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
43+
38|[Count and Say](./0038-count-and-say.js)|Medium|
4344
39|[Combination Sum](./0039-combination-sum.js)|Medium|
4445
40|[Combination Sum II](./0040-combination-sum-ii.js)|Medium|
4546
41|[First Missing Positive](./0041-first-missing-positive.js)|Hard|

‎solutions/0038-count-and-say.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 38. Count and Say
3+
* https://leetcode.com/problems/count-and-say/
4+
* Difficulty: Medium
5+
*
6+
* The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
7+
* - countAndSay(1) = "1"
8+
* - countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is
9+
* then converted into a different digit string.
10+
*
11+
* To determine how you "say" a digit string, split it into the minimal number of substrings such
12+
* that each substring contains exactly one unique digit. Then for each substring, say the number
13+
* of digits, then say the digit. Finally, concatenate every said digit.
14+
*
15+
* For example, the saying and conversion for digit string "3322251":
16+
* Given a positive integer n, return the nth term of the count-and-say sequence.
17+
*/
18+
19+
/**
20+
* @param {number} n
21+
* @return {string}
22+
*/
23+
var countAndSay = function(n) {
24+
let result = '1';
25+
26+
for (let i = 1; i < n; i++) {
27+
result = result.replace(/((\d)\2*)/g, '$1—')
28+
.split('—')
29+
.map(s => s ? `${s.length}${s[0]}` : '')
30+
.join('');
31+
}
32+
33+
return result;
34+
};
35+

0 commit comments

Comments
 (0)
Please sign in to comment.