打印所有可以通过替换通配符“?”形成的平衡括号字符串
给定包含字符'?'、'('和')'的字符串str ,任务是替换'?'带有'('或')'的字符并打印所有包含平衡括号的字符串
例子:
Input: str = “????”
Output:
()()
(())
Input: str = “(()?”
Output: (())
方法:给定的问题可以使用递归和回溯来解决。这个想法是替换每个“?”带有')' 的字符然后递归调用下一个索引,回溯后将其更改为'('然后递归调用下一个索引,回溯后将字符更改回'?' 。按照以下步骤解决问题:
- 将字符串str转换为字符数组,例如ch
- 将字符数组ch和索引0 作为递归函数内的参数传递,并在每次递归调用时执行以下操作:
- 如果索引等于字符数组的长度:
- 检查字符数组是否为平衡括号字符串
- 如果上述条件为真,则打印字符串
- 如果当前字符ch[index]是'('或')'则对下一个索引进行递归调用
- 如果当前字符ch[index]是 '?'然后:
- 将其替换为'('并在下一个索引上进行递归调用
- 将其替换为')'并对下一个索引进行递归调用
- 将其改回“?”从函数返回之前
- 如果索引等于字符数组的长度:
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to print the
// characters of the string
void print(string ch)
{
for (char c : ch) {
cout << c;
}
cout << endl;
}
// Function to check if the
// brackets are valid or not
bool check(string ch)
{
// Initialize a stack
stack S;
// If character is an open bracket
// then return false
if (ch[0] == ')') {
return false;
}
// Iterate the character array
for (int i = 0; i < ch.length(); i++) {
// If character is an open bracket
// then push it in the stack
if (ch[i] == '(') {
S.push('(');
}
// If character is a close bracket
else {
// If stack is empty, there is no
// corresponding opening bracket
// so return false
if (S.size() == 0)
return false;
// Else pop the corresponding
// opening bracket from the stack
else
S.pop();
}
}
// If no opening bracket remains
// then return true
if (S.size() == 0)
return true;
// If there are opening brackets
// then return false
else
return false;
}
// Function to find number of
// strings having balanced brackets
void count(string ch, int index)
{
// Reached end of character array
if (index == ch.length()) {
// Check if the character array
// contains balanced string
if (check(ch)) {
// If it is a balanced string
// then print its characters
print(ch);
}
return;
}
if (ch[index] == '?') {
// replace ? with (
ch[index] = '(';
count(ch, index + 1);
// replace ? with )
ch[index] = ')';
count(ch, index + 1);
// backtrack
ch[index] = '?';
}
else {
// If current character is a
// valid bracket then continue
// to the next character
count(ch, index + 1);
}
}
// Driver function
int main()
{
string ch = "????";
// Call the function
count(ch, 0);
return 0;
}
// This code is contributed by Potta Lokesh
Java
// Java implementation for the above approach
import java.io.*;
import java.util.*;
class Main {
// Function to print the
// characters of the string
static void print(char ch[])
{
for (Character c : ch) {
System.out.print(c);
}
System.out.println();
}
// Function to check if the
// brackets are valid or not
static boolean check(char ch[])
{
// Initialize a stack
Stack S = new Stack<>();
// If character is an open bracket
// then return false
if (ch[0] == ')') {
return false;
}
// Iterate the character array
for (int i = 0; i < ch.length; i++) {
// If character is an open bracket
// then push it in the stack
if (ch[i] == '(') {
S.add('(');
}
// If character is a close bracket
else {
// If stack is empty, there is no
// corresponding opening bracket
// so return false
if (S.size() == 0)
return false;
// Else pop the corresponding
// opening bracket from the stack
else
S.pop();
}
}
// If no opening bracket remains
// then return true
if (S.size() == 0)
return true;
// If there are opening brackets
// then return false
else
return false;
}
// Function to find number of
// strings having balanced brackets
static void count(char ch[], int index)
{
// Reached end of character array
if (index == ch.length) {
// Check if the character array
// contains balanced string
if (check(ch)) {
// If it is a balanced string
// then print its characters
print(ch);
}
return;
}
if (ch[index] == '?') {
// replace ? with (
ch[index] = '(';
count(ch, index + 1);
// replace ? with )
ch[index] = ')';
count(ch, index + 1);
// backtrack
ch[index] = '?';
}
else {
// If current character is a
// valid bracket then continue
// to the next character
count(ch, index + 1);
}
}
// Driver function
public static void main(String[] args)
{
String m = "????";
char ch[] = m.toCharArray();
// Call the function
count(ch, 0);
}
}
Python3
# Python code for the above approach
# Function to print the
# characters of the string
def printf(ch):
for c in ch:
print(c, end="");
print("");
# Function to check if the
# brackets are valid or not
def check(ch):
# Initialize a stack
S = [];
# If character is an open bracket
# then return false
if (ch[0] == ')'):
return False;
# Iterate the character array
for i in range(len(ch)):
# If character is an open bracket
# then push it in the stack
if (ch[i] == '('):
S.append('(');
# If character is a close bracket
else:
# If stack is empty, there is no
# corresponding opening bracket
# so return false
if (len(S) == 0):
return False;
# Else pop the corresponding
# opening bracket from the stack
else:
S.pop();
# If no opening bracket remains
# then return true
if (len(S) == 0):
return True;
# If there are opening brackets
# then return false
else:
return False;
# Function to find number of
# strings having balanced brackets
def count(ch, index):
# Reached end of character array
if (index == len(ch)):
# Check if the character array
# contains balanced string
if (check(ch)):
# If it is a balanced string
# then print its characters
printf(ch);
return;
if (ch[index] == '?'):
# replace ? with (
ch[index] = '(';
count(ch, index + 1);
# replace ? with )
ch[index] = ')';
count(ch, index + 1);
# backtrack
ch[index] = '?';
else:
# If current character is a
# valid bracket then continue
# to the next character
count(ch, index + 1);
# Driver function
ch = "????";
# Call the function
count(list(ch), 0);
# This code is contributed by Saurabh Jaiswal
C#
// C# implementation for the above approach
using System;
using System.Collections;
public class Gfg{
// Function to print the
// characters of the string
static void print(char []ch)
{
foreach (char c in ch) {
Console.Write(c);
}
Console.WriteLine();
}
// Function to check if the
// brackets are valid or not
static bool check(char []ch)
{
// Initialize a stack
Stack S = new Stack();
// If character is an open bracket
// then return false
if (ch[0] == ')') {
return false;
}
// Iterate the character array
for (int i = 0; i < ch.Length; i++) {
// If character is an open bracket
// then push it in the stack
if (ch[i] == '(') {
S.Push('(');
}
// If character is a close bracket
else {
// If stack is empty, there is no
// corresponding opening bracket
// so return false
if (S.Count == 0)
return false;
// Else pop the corresponding
// opening bracket from the stack
else
S.Pop();
}
}
// If no opening bracket remains
// then return true
if (S.Count == 0)
return true;
// If there are opening brackets
// then return false
else
return false;
}
// Function to find number of
// strings having balanced brackets
static void count(char []ch, int index)
{
// Reached end of character array
if (index == ch.Length) {
// Check if the character array
// contains balanced string
if (check(ch)) {
// If it is a balanced string
// then print its characters
print(ch);
}
return;
}
if (ch[index] == '?') {
// replace ? with (
ch[index] = '(';
count(ch, index + 1);
// replace ? with )
ch[index] = ')';
count(ch, index + 1);
// backtrack
ch[index] = '?';
}
else {
// If current character is a
// valid bracket then continue
// to the next character
count(ch, index + 1);
}
}
// Driver function
public static void Main(string[] args)
{
string m = "????";
char []ch = m.ToCharArray();
// Call the function
count(ch, 0);
}
}
// This code is contributed by AnkThon
Javascript
输出
(())
()()
时间复杂度: O(N*2^N)
辅助空间: O(N)