Skip to content

Commit ffc00f8

Browse files
authored
Create 038. Count and Say
1 parent 5ced451 commit ffc00f8

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

038. Count and Say

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* @lc app=leetcode id=38 lang=java
3+
*
4+
* [38] Count and Say
5+
*
6+
* https://leetcode.com/problems/count-and-say/description/
7+
*
8+
* algorithms
9+
* Easy (38.98%)
10+
* Total Accepted: 249.1K
11+
* Total Submissions: 637.9K
12+
* Testcase Example: '1'
13+
*
14+
* The count-and-say sequence is the sequence of integers with the first five
15+
* terms as following:
16+
*
17+
*
18+
* 1. 1
19+
* 2. 11
20+
* 3. 21
21+
* 4. 1211
22+
* 5. 111221
23+
*
24+
*
25+
* 1 is read off as "one 1" or 11.
26+
* 11 is read off as "two 1s" or 21.
27+
* 21 is read off as "one 2, then one 1" or 1211.
28+
*
29+
* Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the
30+
* count-and-say sequence.
31+
*
32+
* Note: Each term of the sequence of integers will be represented as a
33+
* string.
34+
*
35+
* Example 1:
36+
* Input: 1
37+
* Output: "1"
38+
*
39+
* Example 2:
40+
* Input: 4
41+
* Output: "1211"
42+
*
43+
*/
44+
class Solution {
45+
public String countAndSay(int n) {
46+
if(n <= 0) {
47+
return "";
48+
}
49+
50+
String result = "1";
51+
int start = 1;
52+
53+
while(start < n) {
54+
StringBuilder str = new StringBuilder();
55+
int count = 1;
56+
57+
for(int i = 1; i < result.length(); i++) {
58+
if(result.charAt(i) == result.charAt(i-1)) {
59+
count++;
60+
}
61+
else {
62+
str.append(count);
63+
str.append(result.charAt(i-1));
64+
count = 1;
65+
}
66+
}
67+
68+
str.append(count);
69+
str.append(result.charAt(result.length()-1));
70+
result = str.toString();
71+
start++;
72+
}
73+
74+
return result;
75+
}
76+
}

0 commit comments

Comments
 (0)