-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountAndSay.java
More file actions
42 lines (37 loc) · 848 Bytes
/
CountAndSay.java
File metadata and controls
42 lines (37 loc) · 848 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
31
32
33
34
35
36
37
38
39
40
41
42
package questions100;
public class CountAndSay {
public String countAndSay(int n) {
// Start typing your Java solution below
// DO NOT write main() function
//String result = new String();
if (n== 0)
{
return new String();
}
if(n == 1)
{
return new String("1");
}
String last = countAndSay(n-1);
StringBuffer sb = new StringBuffer();
char prev = last.charAt(0);
int times = 0;
for(char c:last.toCharArray())
{
if(c == prev)
{
times ++;
}
else
{
sb.append(times);
sb.append(prev);
prev = c;
times = 1;
}
}
sb.append(times);
sb.append(prev);
return sb.toString();
}
}