Heim Backend-Entwicklung PHP-Tutorial Mindestanzahl an Swaps, um die Saite auszubalancieren

Mindestanzahl an Swaps, um die Saite auszubalancieren

Oct 09, 2024 am 06:08 AM

Minimum Number of Swaps to Make the String Balanced

1963. Minimum Number of Swaps to Make the String Balanced

Difficulty: Medium

Topics: Two Pointers, String, Stack, Greedy

You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.

A string is called balanced if and only if:

  • It is the empty string, or
  • It can be written as AB, where both A and B are balanced strings, or
  • It can be written as [C], where C is a balanced string.

You may swap the brackets at any two indices any number of times.

Return the minimum number of swaps to make s balanced.

Example 1:

  • Input: s = "][]["
  • Output: 1
  • Explanation: You can make the string balanced by swapping index 0 with index 3.
    • The resulting string is "[[]]".

Example 2:

  • Input: s = "]]][[["
  • Output: 2
  • Explanation: You can do the following to make the string balanced:
    • Swap index 0 with index 4. s = "[]][][".
    • Swap index 1 with index 5. s = "[[][]]".
    • The resulting string is "[[][]]".

Example 3:

  • Input: s = "[]"
  • Output: 0
  • Explanation: The string is already balanced.

Constraints:

  • n == s.length
  • 2 <= n <= 106
  • n is even.
  • s[i] is either '[' or ']'.
  • The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.

Hint:

  1. Iterate over the string and keep track of the number of opening and closing brackets on each step.
  2. If the number of closing brackets is ever larger, you need to make a swap.
  3. Swap it with the opening bracket closest to the end of s.

Solution:

We can use a two-pointers approach, which is efficient given the constraints.

Approach:

  1. Track Balance: As we iterate through the string, we can track the balance between opening and closing brackets:

    • Increment the balance when encountering '['.
    • Decrement the balance when encountering ']'.
  2. Identify Imbalance: When the balance becomes negative, it indicates that there are more closing brackets ']' than opening brackets '[' at that point in the string. This is where we need to swap brackets to make the string balanced.

  3. Count Swaps: To correct an imbalance:

    • Keep a counter max_imbalance to track the maximum imbalance observed during the iteration.
    • The required number of swaps is equal to (max_imbalance + 1) / 2, which effectively gives the minimum number of swaps needed to make the string balanced.

Let's implement this solution in PHP: 1963. Minimum Number of Swaps to Make the String Balanced






Explanation:

  1. Balance Tracking:

    • balance keeps track of the difference between the number of '[' and ']'.
    • If balance becomes negative, it indicates that there are more ']' than '[' at that point.
  2. Calculate Maximum Imbalance:

    • max_imbalance stores the largest imbalance encountered during the iteration.
    • If balance becomes negative, update max_imbalance with the larger of max_imbalance or -balance.
  3. Calculate Swaps:

    • To fix an imbalance, the minimum swaps required is (max_imbalance + 1) / 2.

Time Complexity:

  • The time complexity is O(n), where n is the length of the string. We iterate through the string once to determine the max_imbalance.
  • The space complexity is O(1) as we use a few variables for tracking the balance and maximum imbalance.

This solution ensures that we meet the constraints, even for large inputs.

Contact Links

如果您發現本系列有幫助,請考慮在 GitHub 上給 存儲庫 一個星號或在您最喜歡的社交網絡上分享該帖子? 。您的支持對我來說意義重大!

如果您想要更多類似的有用內容,請隨時關注我:

  • 領英
  • GitHub

Das obige ist der detaillierte Inhalt vonMindestanzahl an Swaps, um die Saite auszubalancieren. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

R.E.P.O. Energiekristalle erklärten und was sie tun (gelber Kristall)
2 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Repo: Wie man Teamkollegen wiederbelebt
4 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Abenteuer: Wie man riesige Samen bekommt
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

11 beste PHP -URL -Shortener -Skripte (kostenlos und Premium) 11 beste PHP -URL -Shortener -Skripte (kostenlos und Premium) Mar 03, 2025 am 10:49 AM

11 beste PHP -URL -Shortener -Skripte (kostenlos und Premium)

Einführung in die Instagram -API Einführung in die Instagram -API Mar 02, 2025 am 09:32 AM

Einführung in die Instagram -API

Arbeiten mit Flash -Sitzungsdaten in Laravel Arbeiten mit Flash -Sitzungsdaten in Laravel Mar 12, 2025 pm 05:08 PM

Arbeiten mit Flash -Sitzungsdaten in Laravel

Erstellen Sie eine React -App mit einem Laravel -Back -Ende: Teil 2, reagieren Erstellen Sie eine React -App mit einem Laravel -Back -Ende: Teil 2, reagieren Mar 04, 2025 am 09:33 AM

Erstellen Sie eine React -App mit einem Laravel -Back -Ende: Teil 2, reagieren

Vereinfachte HTTP -Reaktion verspottet in Laravel -Tests Vereinfachte HTTP -Reaktion verspottet in Laravel -Tests Mar 12, 2025 pm 05:09 PM

Vereinfachte HTTP -Reaktion verspottet in Laravel -Tests

Curl in PHP: So verwenden Sie die PHP -Curl -Erweiterung in REST -APIs Curl in PHP: So verwenden Sie die PHP -Curl -Erweiterung in REST -APIs Mar 14, 2025 am 11:42 AM

Curl in PHP: So verwenden Sie die PHP -Curl -Erweiterung in REST -APIs

12 Beste PHP -Chat -Skripte auf Codecanyon 12 Beste PHP -Chat -Skripte auf Codecanyon Mar 13, 2025 pm 12:08 PM

12 Beste PHP -Chat -Skripte auf Codecanyon

Ankündigung von 2025 PHP Situation Survey Ankündigung von 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

Ankündigung von 2025 PHP Situation Survey

See all articles