38. Count and Say #1574
-
Topics: The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string Given a positive integer Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to generate the nth term of the count-and-say sequence. The sequence starts with "1" and each subsequent term is generated by describing the previous term using run-length encoding. Approach
Let's implement this solution in PHP: 38. Count and Say <?php
/**
* @param Integer $n
* @return String
*/
function countAndSay($n) {
if ($n == 1) {
return "1";
}
$current = "1";
for ($i = 2; $i <= $n; $i++) {
$next = "";
$len = strlen($current);
$currentChar = $current[0];
$count = 1;
for ($j = 1; $j < $len; $j++) {
if ($current[$j] == $currentChar) {
$count++;
} else {
$next .= $count . $currentChar;
$currentChar = $current[$j];
$count = 1;
}
}
$next .= $count . $currentChar;
$current = $next;
}
return $current;
}
// Test
echo countAndSay(4); // Output: 1211
echo countAndSay(1); // Output: 1
?> Explanation:
This approach efficiently builds each term iteratively, ensuring that each term is generated by describing the previous term using run-length encoding. The time complexity is O(n * m), where m is the maximum length of any term up to n, which is manageable given the constraints (n ≤ 30). |
Beta Was this translation helpful? Give feedback.
We need to generate the nth term of the count-and-say sequence. The sequence starts with "1" and each subsequent term is generated by describing the previous term using run-length encoding.
Approach