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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP