-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountAndSay.java
33 lines (24 loc) · 963 Bytes
/
CountAndSay.java
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
class CountAndSay {
public static void main(String[] args) {
System.out.println(countAndSay(3));
}
public static String countAndSay(int n) {// Eg 3 ie 21
String s = "1";
for (int i = 1; i < n; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 1, count = 1; j <= s.length(); j++) {
if (j == s.length() || s.charAt(j - 1) != s.charAt(j)) {
//System.out.println("IN IF " + s + " SB " +sb);
sb.append(count);
sb.append(s.charAt(j - 1));
count = 1;
//System.out.println("IN IF END " + s + " SB: " +sb + " co: "+count);
} else {
count++;
}
}
s = sb.toString();
}
return s;
}
}