给定一个由字符‘(‘, ‘)’, ‘[‘, ‘]’, ‘{‘, ‘}’组成的字符串S ,任务是从字符串删除所有平衡括号子序列并打印剩余的字符。
例子:
Input: S = “((){()({})”
Output: “({“
Explanation:
- S[1] and S[2] forms a regular bracket sequence. Therefore, remove them from the string. S = “({()({})”
- S[2] and S[3] are regular bracket sequence. Therefore, remove them from the string. S = “({({})”
- String S[2…4] is regular bracket sequence. Therefore, remove them from the string. S = “({“
Remaining string does not contain any regular bracket sequence. Therefore, print all remaining characters.
Input: S = “{[}])(“
Output: “)(”
做法:思路是使用Stack数据结构来解决这个问题。请按照以下步骤解决问题:
- 初始化三个堆栈,比如A 、 B和C ,用于存储每种类型的括号。
- 初始化一个布尔数组,比如vis[] ,以标记已经访问过的字符。
- 将 char ‘(‘ 的索引存储在堆栈A 中。类似地,堆栈B和C存储字符串中‘{‘和‘[‘的位置。
- 遍历字符串str的字符并执行以下操作:
- 如果当前字符是 ‘ ) ‘:
- 如果堆栈A不为空,则将字符串的当前字符和vis[A.top()]标记为false 。
- 弹出堆栈A的顶部元素。
- 如果当前字符是’ }’:
- 如果堆栈B不为空,则将字符串的当前字符和vis[B.top()]标记为false 。
- 弹出栈B的顶部元素。
- 如果当前字符是‘]’:
- 如果堆栈C不为空,则将字符串的当前字符和vis[C.top()]标记为false。
- 弹出堆栈C的顶部元素。
- 如果当前字符是 ‘ ) ‘:
- 完成所有操作后,打印vis[]数组中索引为true的字符串的字符。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
// Function to remove all possible valid
// bracket subsequences
void removeValidBracketSequences(string& str,
int N)
{
// Stores indexes of '(' in
// valid subsequences
stack A;
// Stores indexes of '{' in
// valid subsequences
stack B;
// Stores indexes of '[' in
// valid subsequences
stack C;
// vis[i]: Check if character at
// i-th index is removed or not
bool vis[N];
// Mark vis[i] as not removed
memset(vis, true, sizeof(vis));
// Iterate over the characters of string
for (int i = 0; i < N; i++) {
// If current character is '('
if (str[i] == '(') {
A.push(i);
}
// If current character is '{'
else if (str[i] == '{') {
B.push(i);
}
// If current character is '['
else if (str[i] == '[') {
C.push(i);
}
// If current character is ')' and
// top element of A is '('
else if (str[i] == ')' && !A.empty()) {
// Mark the top element
// of A as removed
vis[A.top()] = false;
A.pop();
// Mark current chacracter
// as removed
vis[i] = false;
}
// If current character is '}' and
// top element of B is '{'
else if (str[i] == '}' && !B.empty()) {
// Mark the top element
// of B as removed
vis[B.top()] = false;
B.pop();
// Mark current chacracter
// as removed
vis[i] = false;
}
// If current character is ']' and
// top element of B is '['
else if (str[i] == ']' && !C.empty()) {
// Mark the top element
// of C as removed
vis[C.top()] = false;
C.pop();
// Mark current chacracter
// as removed
vis[i] = false;
}
}
// Print the remaining characters
// which is not removed from S
for (int i = 0; i < N; ++i) {
if (vis[i])
cout << str[i];
}
}
// Driver Code
int main()
{
// Given string
string str = "((){()({})";
// Size of the string
int N = str.length();
// Function Call
removeValidBracketSequences(str, N);
return 0;
}
Java
// Java program of the above approach
import java.util.*;
public class GFG
{
// Function to remove all possible valid
// bracket subsequences
static void removeValidBracketSequences(String str, int N)
{
// Stores indexes of '(' in
// valid subsequences
Vector A = new Vector();
// Stores indexes of '{' in
// valid subsequences
Vector B = new Vector();
// Stores indexes of '[' in
// valid subsequences
Vector C = new Vector();
// vis[i]: Check if character at
// i-th index is removed or not
boolean[] vis = new boolean[N];
// Mark vis[i] as not removed
for(int i = 0; i < N; i++)
{
vis[i] = true;
}
// Iterate over the characters of string
for (int i = 0; i < N; i++) {
// If current character is '('
if (str.charAt(i) == '(') {
A.add(i);
}
// If current character is '{'
else if (str.charAt(i) == '{') {
B.add(i);
}
// If current character is '['
else if (str.charAt(i) == '[') {
C.add(i);
}
// If current character is ')' and
// top element of A is '('
else if (str.charAt(i) == ')' && (A.size() > 0)) {
// Mark the top element
// of A as removed
vis[A.get(A.size() - 1)] = false;
A.remove(A.size() - 1);
// Mark current chacracter
// as removed
vis[i] = false;
}
// If current character is '}' and
// top element of B is '{'
else if (str.charAt(i) == '}' && (B.size() > 0)) {
// Mark the top element
// of B as removed
vis[B.get(B.size() - 1)] = false;
B.remove(B.size() - 1);
// Mark current chacracter
// as removed
vis[i] = false;
}
// If current character is ']' and
// top element of B is '['
else if (str.charAt(i) == ']' && (C.size() > 0)) {
// Mark the top element
// of C as removed
vis[C.get(C.size() - 1)] = false;
C.remove(C.size() - 1);
// Mark current chacracter
// as removed
vis[i] = false;
}
}
// Print the remaining characters
// which is not removed from S
for (int i = 0; i < N; ++i)
{
if (vis[i])
System.out.print(str.charAt(i));
}
}
// Driver code
public static void main(String[] args)
{
// Given string
String str = "((){()({})";
// Size of the string
int N = str.length();
// Function Call
removeValidBracketSequences(str, N);
}
}
// This code is contributed by divyeshrabadiya07.
Python3
# Python3 program of the above approach
# Function to remove all possible valid
# bracket subsequences
def removeValidBracketSequences(str, N):
# Stores indexes of '(' in
# valid subsequences
A = []
# Stores indexes of '{' in
# valid subsequences
B = []
# Stores indexes of '[' in
# valid subsequences
C = []
# vis[i]: Check if character at
# i-th index is removed or not
vis = [True for i in range(N)]
# Iterate over the characters of string
for i in range(N):
# If current character is '('
if (str[i] == '('):
A.append(i)
# If current character is '{'
elif (str[i] == '{'):
B.append(i)
# If current character is '['
elif (str[i] == '['):
C.append(i)
# If current character is ')' and
# top element of A is '('
elif(str[i] == ')' and len(A) != 0):
# Mark the top element
# of A as removed
vis[A[-1]] = False
A.pop()
# Mark current chacracter
# as removed
vis[i] = False
# If current character is '}' and
# top element of B is '{'
elif (str[i] == '}' and len(B) != 0):
# Mark the top element
# of B as removed
vis[B[-1]] = False
B.pop()
# Mark current chacracter
# as removed
vis[i] = False
# If current character is ']' and
# top element of B is '['
elif(str[i] == ']' and len(C) != 0):
# Mark the top element
# of C as removed
vis[C[-1]] = False
C.pop()
# Mark current chacracter
# as removed
vis[i] = False
# Print the remaining characters
# which is not removed from S
for i in range(N):
if (vis[i]):
print(str[i], end = '')
# Driver Code
if __name__=='__main__':
# Given string
str = "((){()({})"
# Size of the string
N = len(str)
# Function Call
removeValidBracketSequences(str, N)
# This code is contributed by rutvik_56
C#
// C# program of the above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to remove all possible valid
// bracket subsequences
static void removeValidBracketSequences(string str, int N)
{
// Stores indexes of '(' in
// valid subsequences
List A = new List();
// Stores indexes of '{' in
// valid subsequences
List B = new List();
// Stores indexes of '[' in
// valid subsequences
List C = new List();
// vis[i]: Check if character at
// i-th index is removed or not
bool[] vis = new bool[N];
// Mark vis[i] as not removed
for(int i = 0; i < N; i++)
{
vis[i] = true;
}
// Iterate over the characters of string
for (int i = 0; i < N; i++) {
// If current character is '('
if (str[i] == '(') {
A.Add(i);
}
// If current character is '{'
else if (str[i] == '{') {
B.Add(i);
}
// If current character is '['
else if (str[i] == '[') {
C.Add(i);
}
// If current character is ')' and
// top element of A is '('
else if (str[i] == ')' && (A.Count > 0)) {
// Mark the top element
// of A as removed
vis[A[A.Count - 1]] = false;
A.RemoveAt(A.Count - 1);
// Mark current chacracter
// as removed
vis[i] = false;
}
// If current character is '}' and
// top element of B is '{'
else if (str[i] == '}' && (B.Count > 0)) {
// Mark the top element
// of B as removed
vis[B[B.Count - 1]] = false;
B.RemoveAt(B.Count - 1);
// Mark current chacracter
// as removed
vis[i] = false;
}
// If current character is ']' and
// top element of B is '['
else if (str[i] == ']' && (C.Count > 0)) {
// Mark the top element
// of C as removed
vis[C[C.Count - 1]] = false;
C.RemoveAt(C.Count - 1);
// Mark current chacracter
// as removed
vis[i] = false;
}
}
// Print the remaining characters
// which is not removed from S
for (int i = 0; i < N; ++i) {
if (vis[i])
Console.Write(str[i]);
}
}
// Driver code
static void Main()
{
// Given string
string str = "((){()({})";
// Size of the string
int N = str.Length;
// Function Call
removeValidBracketSequences(str, N);
}
}
// This code is contributed by divyesh072019.
Javascript
输出:
({
时间复杂度: O(N)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live