Count and Say | String Problem | LeetCode 38
4 years ago Lalit Bhagtani 0
Problem Statement
Count and Say sequence is the sequence of integers as following :-
- 1 (one times 1, so next integer in sequence is 11)
- 11 (two times 1, so next integer in sequence is 21)
- 21 (one times 2 and one times 1, so next integer in sequence is 1211)
- 1211
You have given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count and say sequence.
Example
Input :- 4 Output :- 1211
Input :- 11 Output :- 11131221133112132113212221
Solution
This problem can be solved in following steps :-
- Recursively start from the n-1 and go to 1.
- After reaching integer 1, evaluate its count and say string and return it.
- Use the count and say string return by the previous function call to evaluate the next count and say string.
- Repeat steps 3, till the end of all the function calls.
Program
public class Main { public static void main(String[] args) { Main main = new Main(); String result = main.countAndSay(11); System.out.print(result); } /* Solution */ public String countAndSay(int n) { if(n == 1 || n == 0) return "1"; String previous = countAndSay(n - 1); int count = 0; StringBuilder sb = new StringBuilder(); char[] preArray = previous.toCharArray(); char preChar = preArray[0]; for(char c : preArray){ if(c == preChar){ count++; }else { sb.append(Integer.toString(count) + preChar); count = 1; preChar = c; } } sb.append(Integer.toString(count) + preChar); return sb.toString(); } }
Result
11131221133112132113212221