C++中交換和移除字元後平衡字串的最大長度


給定一個字串,其中只包含 (,),{,},[,] 字元。目標是找到該字串的最大長度,使其透過交換相鄰字元或移除字元後變得平衡。(}{,)(,][ 可以交換,而 {{,)),[[,}},)),]] 不能交換)。

如果一個字元沒有匹配的配對字元,也可以將其移除。(例如:“{{}][“, 這裡第一個 { 可以移除,平衡字串長度變為 4)

輸入

str[]= “ {{{}}{]]][()” length 12

輸出

Maximum length of balances string: 8

解釋 − str[0] 和 str[1] 不能交換,移除 str[0]= “{{}}{]]][()” str[1] 和 str[2] 不能交換,移除 str[1]= “{}}{]]][()” {} 是平衡的,}{ 可以交換,移除接下來的兩個 ]], 交換 ][ 和 () 也是平衡的。最終字串是 {}{}[]()。長度是 8。

輸入

str[]= “(((((()” length 7

輸出

str[]= “(((((()” length 7

解釋 − 只有 str[5] 和 str[6] 是平衡的,移除所有其他字元。最終字串 ()。長度是 2。

下面程式中使用的方法如下

  • 字元陣列 str[] 儲存原始字串。整數 Length 儲存字串的長度。

  • 函式 maxBalancedStr (char str[], int len) 以字串及其長度作為引數,並返回平衡字串的最大長度。

  • 變數 count 用於儲存該字串的長度,初始值為 0。

  • 從第一個字元開始遍歷字串,並檢查相鄰字元是否可以交換以使它們都平衡。或者如果它們已經是平衡的,則將 count 加 2。

  • 對像 (),)( 和 {},}{ 和 [],][ 這樣的對執行此操作,如果存在這樣的對,則也遞增 i,以移動到下一個字元。

  • 最後,count 儲存平衡字串的長度。

  • 返回 count 作為結果。

示例

 線上演示

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the length of
// the longest balanced sub-string
int maxBalancedStr(char str[20], int len){
   int count=0;
   // Traversing the string
   for (int i = 0; i <len;i++) {
      // Check type of parentheses and
      // incrementing count for it
      if((str[i]=='(' && str[i+1]==')') || (str[i]==')' && str[i+1]=='(')) //can swap{
         count+=2; ++i; }
      else if((str[i]=='{' && str[i+1]=='}') || (str[i]=='}' && str[i+1]=='{')) //can swap{
         count+=2; ++i; }
      else if((str[i]=='[' && str[i+1]==']') || (str[i]==']' && str[i+1]=='[')) //can swap          count+=2; ++i; }
   }
   return count;
}
// Driven code
int main(){
   char str[] = ")([]]((";
   int length=7;
   cout << maxBalancedStr(str,length);
   return 0;
}

輸出

4

更新於:2020年8月3日

91 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.