Home > Backend Development > PHP Tutorial > Construct String With Repeat Limit

Construct String With Repeat Limit

Susan Sarandon
Release: 2024-12-24 08:44:19
Original
750 people have browsed it

Construct String With Repeat Limit

2182. Construct String With Repeat Limit

Difficulty: Medium

Topics: Hash Table, String, Greedy, Heap (Priority Queue), Counting

You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s.

Return the lexicographically largest repeatLimitedString possible.

A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.

Example 1:

  • Input: s = "cczazcc", repeatLimit = 3
  • Output: "zzcccac"
  • Explanation: We use all of the characters from s to construct the repeatLimitedString "zzcccac".
    • The letter 'a' appears at most 1 time in a row.
    • The letter 'c' appears at most 3 times in a row.
    • The letter 'z' appears at most 2 times in a row.
    • Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.
    • The string is the lexicographically largest repeatLimitedString possible so we return "zzcccac".
    • Note that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.

Example 2:

  • Input: s = "aababab", repeatLimit = 2
  • Output: "bbabaa"
  • Explanation: We use only some of the characters from s to construct the repeatLimitedString "bbabaa".
    • The letter 'a' appears at most 2 times in a row.
    • The letter 'b' appears at most 2 times in a row.
    • Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.
    • The string is the lexicographically largest repeatLimitedString possible so we return "bbabaa".
    • Note that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.

Constraints:

  • 1 <= repeatLimit <= s.length <= 105
  • s consists of lowercase English letters.

Hint:

  1. Start constructing the string in descending order of characters.
  2. When repeatLimit is reached, pick the next largest character.

Solution:

We use a greedy approach to prioritize lexicographically larger characters while ensuring that no character exceeds the repeatLimit consecutively. The approach uses a priority queue (max heap) to process characters in lexicographically descending order and ensures that no character appears more than the repeatLimit times consecutively.

Solution Explanation

  1. Count Characters: Count the frequency of each character in the string s using an array.
  2. Max Heap: Use a max heap (priority queue) to sort and extract characters in descending lexicographical order.
  3. Greedy Construction:
    • Add the largest character available up to repeatLimit times.
    • If the repeatLimit for the current character is reached, switch to the next largest character, insert it once, and then reinsert the first character into the heap for further use.
  4. Edge Handling: Properly manage when a character cannot be used any further.

Let's implement this solution in PHP: 2182. Construct String With Repeat Limit

<?php
/**
 * @param String $s
 * @param Integer $repeatLimit
 * @return String
 */
function repeatLimitedString($s, $repeatLimit) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */

}

// Test Cases
echo repeatLimitedString("cczazcc", 3) . "\n"; // Output: zzcccac
echo repeatLimitedString("aababab", 2) . "\n"; // Output: bbabaa
?>




<h3>
  
  
  Explanation:
</h3>

<ol>
<li>
<p><strong>Frequency Count:</strong></p>

<ul>
<li>Iterate through the string s to count the occurrences of each character.</li>
<li>Store the frequency in an associative array $freq.</li>
</ul>
</li>
<li>
<p><strong>Sort in Descending Order:</strong></p>

<ul>
<li>Use krsort() to sort the characters by their lexicographical order in <strong>descending</strong> order.</li>
</ul>
</li>
<li>
<p><strong>Build the Result:</strong></p>

<ul>
<li>Continuously append the lexicographically largest character ($char) to the result string.</li>
<li>If a character reaches its repeatLimit, stop appending it temporarily.</li>
<li>Use a temporary queue to hold characters that still have remaining counts but are temporarily skipped.</li>
</ul>
</li>
<li>
<p><strong>Handle Repeat Limit:</strong></p>

<ul>
<li>If the current character has hit the repeatLimit, use the next lexicographically largest character from the queue.</li>
<li>Reinsert the previous character back into the frequency map to continue processing it later.</li>
</ul>
</li>
<li>
<p><strong>Edge Cases:</strong></p>
<ul>
<li>Characters may not use up their full counts initially.</li>
<li>After handling a backup character from the queue, the current character resumes processing.</li>
</ul>
</li>
</ol>

<h3>
  
  
  <strong>How It Works</strong>
</h3>

<ol>
<li>
<strong>Character Count</strong>: $freq keeps track of occurrences for all characters.</li>
<li>
<strong>Max Heap</strong>: SplPriorityQueue is used as a max heap, where characters are prioritized by their ASCII value (descending order).</li>
<li>
<strong>String Construction</strong>:

<ul>
<li>If the current character has reached its repeatLimit, fetch the next largest character.</li>
<li>Use the next largest character once and reinstate the previous character into the heap for future use.</li>
</ul>
</li>
<li>
<strong>Final Result</strong>: The resulting string is the lexicographically largest string that satisfies the repeatLimit constraint.</li>
</ol>

<h3>
  
  
  <strong>Example Walkthrough</strong>
</h3>

<p><strong>Input:</strong><br><br>
s = "cczazcc", repeatLimit = 3</p>

<p><strong>Steps:</strong></p>

<ol>
<li><p>Frequency count:<br><br>
['a' => 1, 'c' => 4, 'z' => 2]</p></li>
<li><p>Sort in descending order:<br><br>
['z' => 2, 'c' => 4, 'a' => 1]</p></li>
<li>
<p>Append characters while respecting repeatLimit:</p>

<ul>
<li>Append 'z' → "zz" (z count = 0)</li>
<li>Append 'c' 3 times → "zzccc" (c count = 1)</li>
<li>Append 'a' → "zzccca" (a count = 0)</li>
<li>Append remaining 'c' → "zzcccac"</li>
</ul>
</li>
</ol>

<p><strong>Output:</strong> "zzcccac"</p>

<h3>
  
  
  <strong>Time Complexity</strong>
</h3>

<ul>
<li>
<strong>Character Frequency Counting</strong>: <em><strong>O(n)</strong></em>, where <em><strong>n</strong></em> is the length of the string.</li>
<li>
<strong>Heap Operations</strong>: <em><strong>O(26 log 26)</strong></em>, as the heap can hold up to 26 characters.</li>
<li>
<strong>Overall Complexity</strong>: <em><strong>O(n   26 log 26) ≈ O(n)</strong></em>.</li>
</ul>

<h3>
  
  
  <strong>Space Complexity</strong>
</h3>

<ul>
<li>
<em><strong>O(26)</strong></em> for the frequency array.</li>
<li>
<em><strong>O(26)</strong></em> for the heap.</li>
</ul>

<h3>
  
  
  <strong>Test Cases</strong>
</h3>



<pre class="brush:php;toolbar:false"><?php
/**
 * @param String $s
 * @param Integer $repeatLimit
 * @return String
 */
function repeatLimitedString($s, $repeatLimit) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */

}

// Test Cases
echo repeatLimitedString("cczazcc", 3) . "\n"; // Output: zzcccac
echo repeatLimitedString("aababab", 2) . "\n"; // Output: bbabaa
?>
Copy after login

Edge Cases

  1. s contains only one unique character (e.g., "aaaaaaa", repeatLimit = 2): The output will only include as many characters as allowed consecutively.
  2. repeatLimit = 1: The output alternates between available characters.
  3. All characters in s are unique: The output is sorted in descending order.

This implementation works efficiently within the constraints.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

  • LinkedIn
  • GitHub

The above is the detailed content of Construct String With Repeat Limit. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template