package com.javamvc.learning.leetcode;
public class leetcode38countAndSay {
public static void main(String[] args) {
leetcode38countAndSay leetcode38 = new leetcode38countAndSay();
Solution solution = leetcode38.new Solution();
String countAndSay = solution.countAndSay(10);
System.out.println(countAndSay);
}
class Solution {
public String countAndSay(int n) {
if (n == 1) {
return "1";
}
if (n == 2) {
return "11";
}
StringBuilder ans = new StringBuilder();
String previous = countAndSay(n - 1);
for (int i = 1; i < previous.length(); i++) {
int count = 1;
char temp = previous.charAt(i - 1);
while (i < previous.length() && previous.charAt(i) == temp) {
count++;
i++;
}
ans.append(count);
ans.append(temp - '0');
if (i == previous.length() - 1) {
ans.append(1);
ans.append(previous.charAt(previous.length() - 1) - '0');
}
}
return ans.toString();
}
}
}