[LeetCode] 38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:
1.     1
2.     11
3.     21
4.     1211
5.     111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"

Thought process:
More like count and print.

Solution:

 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
class Solution {
    public String countAndSay(int n) {
        String str = "1";
        for (int i = 2; i <= n; i++) {
            str = helper(str);
        }
        return str;
    }
    
    private String helper(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char number = str.charAt(i);
            int count = 0;
            
            while (i < str.length() && str.charAt(i) == number) {
                count++;
                i++;
            }
            i--;
            
            sb.append(count);
            sb.append(number);
        }
        return sb.toString();
    }
}

Time complexity:
Say the average length of the strings is l. The overall time complexity is O(ln).

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. If you count total iterations and plot them against values of n, it's an exponential curve. I suspect that the sequence is ever growing, not oscillating and at each increase of n the dominating length of the string is exponential in n

    ReplyDelete

Post a Comment

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula