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. 1   (one times 1, so next integer in sequence is 11)
  2. 11 (two times 1, so next integer in sequence is 21)
  3. 21 (one times 2 and one times 1, so next integer in sequence is 1211)
  4. 1211 

You have given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count and say sequence.

Example 

Count And Say

Input :- 4
Output :- 1211
Input :- 11
Output :- 11131221133112132113212221

Solution

This problem can be solved in following steps :-

  1. Recursively start from the n-1 and go to 1.
  2. After reaching integer 1, evaluate its count and say string and return it.
  3. Use the count and say string return by the previous function call to evaluate the next count and say string.
  4. 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

Similar Post

  1. Reverse only Letters of a String
  2. Shifting Letters of a String
  3. Custom Order Sorting of String