-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountAndSay.java
More file actions
30 lines (29 loc) · 838 Bytes
/
CountAndSay.java
File metadata and controls
30 lines (29 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
* https://leetcode.com/problems/count-and-say/
*/
public class CountAndSay {
public String countAndSay(int n) {
if (n == 1) {
return "1";
}
String previous = countAndSay(n - 1);
StringBuilder s = new StringBuilder();
char current = previous.charAt(0);
int count = 1;
for (int i = 1; i < previous.length(); i++) {
char c = previous.charAt(i);
if (c == current) {
count++;
} else {
s.append(count).append(current);
current = c;
count = 1;
}
}
s.append(count).append(current);
return s.toString();
}
public static void main(String[] args) {
System.out.println(new CountAndSay().countAndSay(4)); // 1211
}
}