The Count and Say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n)
is the way you would “say” the digit string from countAndSay(n-1)
, which is then converted into a different digit string.To determine how you “say” a digit string, you split it into the minimal number of groups so that each group is a contiguous section all of the same digit. Then for each group, say the number of digits, followed by the digit. You concatenate these descriptions to form the next term.
For example:
"1" is read off as "one 1" → "11".
"11" is read off as "two 1s" → "21".
"21" is read off as "one 2, then one 1" → "1211".
"1211" is read off as "one 1, one 2, then two 1s" → "111221".
Given a positive integer n
, return the n
-th term of the count-and-say sequence.
n
?
1 ≤ n ≤ 30
, but we should ensure sequences are properly handled within this range.countAndSay(1) = "1"
.n
, we generate the next sequence by “saying” the current sequence.public class CountAndSay {
public String countAndSay(int n) {
String result = "1";
for (int i = 1; i < n; i++) {
result = getNextSequence(result);
}
return result;
}
private String getNextSequence(String s) {
StringBuilder nextSeq = new StringBuilder();
int i = 0;
while (i < s.length()) {
char digit = s.charAt(i);
int count = 0;
// Count the number of occurrences of the same digit
while (i < s.length() && s.charAt(i) == digit) {
i++;
count++;
}
// Append the count and the digit to the next sequence
nextSeq.append(count).append(digit);
}
return nextSeq.toString();
}
public static void main(String[] args) {
CountAndSay sol = new CountAndSay();
int n = 5; // Example input
System.out.println(sol.countAndSay(n)); // Output: "111221"
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?