InfyTQ 2019:找到括号不平衡的位置
给定一个字符串str ,由 [ “(” , “)” , “{” , “}” , “[” , “]” ] 的括号组成。
如果字符串完全平衡,则返回 0,否则返回发现嵌套错误的索引(从 1 开始)。
例子:
Input : str = “{[()]}[]”
Output : 0
Input : str = “[{]()}”
Output : 3
Input : str = “}[{}]”
Output : 1
Input : str = “{([]){”
Output : 7
方法:
- 首先,我们创建 lst1 和 lst2,它们将分别具有左括号和右括号
- 现在我们将创建另一个列表 lst 它将作为堆栈工作,这意味着如果任何右括号将出现在字符串中,则将删除 lst 中存在的相应左括号
- 如果任何右括号将出现在字符串中,并且在 lst 中没有相应的左括号,那么这将是错误索引,我们将返回它
- 如果我们在遍历时到达字符串的末尾并且 lst 的大小不等于 0 ,我们将返回 len(String)+1
下面是上述方法的实现
C++
// C++ implementation of the approach
#include
using namespace std;
int main()
{
// Defining the string
string String = "{[()]}[]";
// Storing opening braces in list lst1
vector lst1 ={'{', '(', '['};
// Storing closing braces in list lst2
vector lst2 ={'}', ')', ']'};
// Creating an empty list lst
vector lst;
int k;
// Creating dictionary to map
// closing braces to opening ones
map Dict;
Dict.insert(pair(')', '('));
Dict.insert(pair('}', '{'));
Dict.insert(pair(']', '['));
int a = 0, b = 0, c = 0;
// If first position of string contain
// any closing braces return 1
if(count(lst2.begin(), lst2.end(), String[0]))
{
cout << 1 << endl;
}
else
{
// If characters of string are opening
// braces then append them in a list
for(int i = 0; i < String.size(); i++)
{
if(count(lst1.begin(), lst1.end(), String[i]))
{
lst.push_back(String[i]);
k = i + 2;
}
else
{
// When size of list is 0 and new closing
// braces is encountered then print its
// index starting from 1
if(lst.size()== 0 && (count(lst2.begin(), lst2.end(), String[i])))
{
cout << (i + 1) << endl;
c = 1;
break;
}
else
{
// As we encounter closing braces we map
// them with theircorresponding opening
// braces using dictionary and check
// if it is same as last opened braces
//(last element in list) if yes then we
// delete that element from list
if(Dict[String[i]]== lst[lst.size()-1])
{
lst.pop_back();
}
else
{
// Otherwise we return the index
// (starting from 1) at which
// nesting is found wrong
break;
cout << (i + 1) << endl;
a = 1;
}
}
}
}
// At end if the list is empty it
// means the string is perfectly nested
if(lst.size() == 0 && c == 0)
{
cout << 0 << endl;
b = 1;
}
if(a == 0 && b == 0 && c == 0)
{
cout << k << endl;
}
}
return 0;
}
// This code is contributed by decode2207.
Java
// Java implementation of the approach
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Defining the string
String string = "{[()]}[]";
// Storing opening braces in list lst1
char[] lst1 = {'{', '(', '['};
// Storing closing braces in list lst2
char[] lst2 = {'}', ')', ']'};
// Creating an empty list lst
Vector lst = new Vector();
// Creating dictionary to map
// closing braces to opening ones
HashMap Dict = new HashMap<>();
Dict.put(')', '(');
Dict.put('}', '{');
Dict.put(']', '[');
int a = 0, b = 0, c = 0;
// If first position of string contain
// any closing braces return 1
if(Arrays.asList(lst2).contains(string.charAt(0)))
{
System.out.println(1);
}
else
{
int k = 0;
// If characters of string are opening
// braces then append them in a list
for(int i = 0; i < string.length(); i++)
{
if(Arrays.asList(lst1).contains(string.charAt(i)))
{
lst.add(string.charAt(i));
k = i + 2;
}
else
{
// When size of list is 0 and new closing
// braces is encountered then print its
// index starting from 1
if(lst.size()== 0 && Arrays.asList(lst2).contains(string.charAt(i)))
{
System.out.println((i + 1));
c = 1;
break;
}
else
{
// As we encounter closing braces we map
// them with theircorresponding opening
// braces using dictionary and check
// if it is same as last opened braces
//(last element in list) if yes then we
// delete that element from list
if(lst.size() > 0 && Dict.get(string.charAt(i))== lst.get(lst.size() - 1))
{
lst.remove(lst.size() - 1);
}
else
{
// Otherwise we return the index
// (starting from 1) at which
// nesting is found wrong
a = 1;
break;
}
}
}
}
// At end if the list is empty it
// means the string is perfectly nested
if(lst.size() == 0 && c == 0)
{
System.out.println(0);
b = 1;
}
if(a == 0 && b == 0 && c == 0)
{
System.out.println(k);
}
}
}
}
// This code is contributed by divyesh072019.
Python3
# Write Python3 code here
# Defining the string
string = "{[()]}[]"
# Storing opening braces in list lst1
lst1 =['{', '(', '[']
# Storing closing braces in list lst2
lst2 =['}', ')', ']']
# Creating an empty list lst
lst =[]
# Creating dictionary to map
# closing braces to opening ones
Dict ={ ')':'(', '}':'{', ']':'['}
a = b = c = 0
# If first position of string contain
# any closing braces return 1
if string[0] in lst2:
print(1)
else:
# If characters of string are opening
# braces then append them in a list
for i in range(0, len(string)):
if string[i] in lst1:
lst.append(string[i])
k = i + 2
else:
# When size of list is 0 and new closing
# braces is encountered then print its
# index starting from 1
if len(lst)== 0 and (string[i] in lst2):
print(i + 1)
c = 1
break
else:
# As we encounter closing braces we map
# them with theircorresponding opening
# braces using dictionary and check
# if it is same as last opened braces
#(last element in list) if yes then we
# delete that element from list
if Dict[string[i]]== lst[len(lst)-1]:
lst.pop()
else:
# Otherwise we return the index
# (starting from 1) at which
# nesting is found wrong
print(i + 1)
a = 1
break
# At end if the list is empty it
# means the string is perfectly nested
if len(lst)== 0 and c == 0:
print(0)
b = 1
if a == 0 and b == 0 and c == 0:
print(k)
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
static void Main()
{
// Defining the string
string String = "{[()]}[]";
// Storing opening braces in list lst1
char[] lst1 = {'{', '(', '['};
// Storing closing braces in list lst2
char[] lst2 = {'}', ')', ']'};
// Creating an empty list lst
List lst = new List();
// Creating dictionary to map
// closing braces to opening ones
Dictionary Dict = new Dictionary();
Dict[')'] = '(';
Dict['}'] = '{';
Dict[']'] = '[';
int a = 0, b = 0, c = 0;
// If first position of string contain
// any closing braces return 1
if(Array.Exists(lst2, element => element == String[0]))
{
Console.WriteLine(1);
}
else
{
int k = 0;
// If characters of string are opening
// braces then append them in a list
for(int i = 0; i < String.Length; i++)
{
if(Array.Exists(lst1, element => element == String[i]))
{
lst.Add(String[i]);
k = i + 2;
}
else
{
// When size of list is 0 and new closing
// braces is encountered then print its
// index starting from 1
if(lst.Count== 0 && Array.Exists(lst2, element => element == String[i]))
{
Console.WriteLine((i + 1));
c = 1;
break;
}
else
{
// As we encounter closing braces we map
// them with theircorresponding opening
// braces using dictionary and check
// if it is same as last opened braces
//(last element in list) if yes then we
// delete that element from list
if(lst.Count > 0 && Dict[String[i]]== lst[lst.Count - 1])
{
lst.RemoveAt(lst.Count - 1);
}
else
{
// Otherwise we return the index
// (starting from 1) at which
// nesting is found wrong
a = 1;
break;
}
}
}
}
// At end if the list is empty it
// means the string is perfectly nested
if(lst.Count == 0 && c == 0)
{
Console.WriteLine(0);
b = 1;
}
if(a == 0 && b == 0 && c == 0)
{
Console.WriteLine(k);
}
}
}
}
// This code is contributed by divyeshrabadiya07.
Javascript
输出:
0