C++ 刪除表示式中無效的括號
給定一個括號序列;現在,您必須列印所有可能的括號,可以透過刪除無效括號來生成,例如
Input : str = “()())()” - Output : ()()() (())() There are two possible solutions "()()()" and "(())()" Input : str = (v)())() Output : (v)()() (v())()
在這個問題中,我們將使用回溯法來列印所有有效的序列。
尋找解決方案的方法
在這種方法中,我們將嘗試使用廣度優先搜尋 (BFS) 一一刪除左括號和右括號。現在,對於每個序列,我們檢查它是否有效。如果有效,則將其列印為輸出。
示例
#include <bits/stdc++.h>
using namespace std;
bool isParenthesis(char c){
return ((c == '(') || (c == ')'));
}
bool validString(string str){
// cout << str << " ";
int cnt = 0;
for (int i = 0; i < str.length(); i++){
if (str[i] == '(')
cnt++;
else if (str[i] == ')')
cnt--;
if (cnt < 0)
return false;
}
// cout << str << " ";
return (cnt == 0);
}
void validParenthesesSequences(string str){
if (str.empty())
return ;
set<string> visit; // if we checked that sting so we put it inside visit
// so that we will not encounter that string again
queue<string> q; // queue for performing bfs
string temp;
bool level;
// pushing given string as starting node into queue
q.push(str);
visit.insert(str);
while (!q.empty()){
str = q.front(); q.pop();
if (validString(str)){
// cout << "s";
cout << str << "\n"; // we print our string
level = true; // as we found the sting on the same level so we don't need to apply bfs from it
}
if (level)
continue;
for (int i = 0; i < str.length(); i++){
if (!isParenthesis(str[i])) // we won't be removing any other characters than the brackets from our string
continue;
temp = str.substr(0, i) + str.substr(i + 1); // removing parentheses from the strings one by one
if (visit.find(temp) == visit.end()) { // if we check that string so we won't check it again
q.push(temp);
visit.insert(temp);
}
}
}
}
int main(){
string s1;
s1 = "(v)())()";
cout << "Input : " << s1 << "\n";
cout << "Output : ";
validParenthesesSequences(s1);
return 0;
}輸出
Input : (v)())() Output : (v())()
上述程式碼的解釋
在上述方法中,我們簡單地一一刪除括號,並且在我們刪除括號的同時,我們也跟蹤之前的序列,這樣我們就不會兩次檢查同一個序列。如果我們從所有這些可能性中找到一個有效的序列,我們將列印所有有效的可能性,這就是我們的程式的執行過程。
結論
在本教程中,我們解決了一個問題,即查詢並刪除無效括號。我們還學習了這個問題的 C++ 程式以及我們解決這個問題的完整方法(常規方法)。我們可以使用 C、Java、Python 等其他語言編寫相同的程式。希望您覺得本教程有所幫助。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP