我正在尝试创建一个程序,将一个字符串作为参数放入其构造函数中。我需要一个方法来检查字符串是否是一个平衡的括号表达式。它需要处理({[]})每个open需要与其相应的右括号进行平衡。例如,用户可以输入[({})],这将是平衡的,而{}将是不平衡的。这不需要处理字母或数字。我需要使用堆栈来执行此操作。
我得到了这个伪代码,但无法想出如何在java中实现它。任何建议都会很棒。
更新 - 抱歉忘了发布我到目前为止的内容。这一切搞砸了,因为起初我试图使用char然后我尝试了一个数组..我不确定去哪里。
import java.util.*;
public class Expression
{
Scanner in = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
public boolean check()
{
System.out.println("Please enter your expression.");
String newExp = in.next();
String[] exp = new String[newExp];
for (int i = 0; i < size; i++)
{
char ch = exp.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(i);
else if (ch == ')'|| ch == ']' || ch == '}')
{
//nothing to match with
if(stack.isEmpty())
{
return false;
}
else if(stack.pop() != ch)
{
return false;
}
}
}
if (stack.isEmpty())
{
return true;
}
else
{
return false;
}
}
}
答案 0 :(得分:34)
我希望这段代码可以提供帮助:
import java.util.Stack;
public class BalancedParenthensies {
public static void main(String args[]) {
System.out.println(balancedParenthensies("{(a,b)}"));
System.out.println(balancedParenthensies("{(a},b)"));
System.out.println(balancedParenthensies("{)(a,b}"));
}
public static boolean balancedParenthensies(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
答案 1 :(得分:9)
public static boolean isBalanced(String expression) {
if ((expression.length() % 2) == 1) return false;
else {
Stack<Character> s = new Stack<>();
for (char bracket : expression.toCharArray())
switch (bracket) {
case '{': s.push('}'); break;
case '(': s.push(')'); break;
case '[': s.push(']'); break;
default :
if (s.isEmpty() || bracket != s.peek()) { return false;}
s.pop();
}
return s.isEmpty();
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String expression = in.nextLine();
boolean answer = isBalanced(expression);
if (answer) { System.out.println("YES");}
else { System.out.println("NO");}
}
答案 2 :(得分:8)
The pseudo code equivalent java implementation of the algorithm is java is as follows.
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* @author Yogen Rai
*/
public class BalancedBracket {
public static void main(String[] args) {
String braces = "{{}(";
if(isBalanced(braces)){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
public static boolean isBalanced(String brackets) {
// set matching pairs
Map<Character, Character> braces = new HashMap<>();
braces.put('(', ')');
braces.put('[',']');
braces.put('{','}');
// if length of string is odd, then it is not balanced
if (brackets.length() % 2 != 0) {
return false;
}
// travel half until openings are found and compare with
// remaining if the closings matches
Stack<Character> halfBraces = new Stack();
for(char ch: brackets.toCharArray()) {
if (braces.containsKey(ch)) {
halfBraces.push(braces.get(ch));
}
// if stack is empty or if closing bracket is not equal to top of stack,
// then braces are not balanced
else if(halfBraces.isEmpty() || ch != halfBraces.pop()) {
return false;
}
}
return halfBraces.isEmpty();
}
}
答案 3 :(得分:3)
使用堆栈将开口符号推到它上是很重要的,然后当你遇到一个右大括号时,你将元素从堆栈的顶部弹出,然后检查它是否与类型匹配关闭括号。这是一个java实现。
import java.util.Stack;
public class Balanced {
public static void main (String [] args)
{
String test_good = "()(){}{}{()}";
String test_bad = "((({}{}))()";
System.out.println(checkBalanced(test_good));
System.out.println(checkBalanced(test_bad));
}
public static boolean checkBalanced(String check)
{
Stack<Character> S = new Stack<Character>();
for(int a = 0; a < check.length(); a++)
{
char let = check.charAt(a);
if(let == '[' || let == '{' || let == '(')
S.push(let);
else if(let == ']' || let == '}' || let == ')')
{
if(S.empty())
return false;
switch(let)
{
// Opening square brace
case ']':
if (S.pop() != '[')
return false;
break;
// Opening curly brace
case '}':
if (S.pop() != '{')
return false;
break;
// Opening paren brace
case ')':
if (S.pop() != '(')
return false;
break;
default:
break;
}
}
}
if(S.empty())
return true;
return false;
}
}
答案 4 :(得分:3)
你介意,如果我要添加基于 JavaScript 的怪异风格的解决方案吗?
这是一个特别的东西,不是为了制作,而是为了采访或类似的东西。或者只是为了好玩。
代码:
function reduceStr (str) {
const newStr = str.replace('()', '').replace('{}', '').replace('[]', '')
if (newStr !== str) return reduceStr(newStr)
return newStr
}
function verifyNesting (str) {
return reduceStr(str).length === 0
}
<强>检查强>:
console.log(verifyNesting('[{{[(){}]}}[]{}{{(())}}]')) //correct
console.log(verifyNesting('[{{[(){}]}}[]{}{({())}}]')) //incorrect
<强>解释强>:
它将递归删除关闭对“()”,“[]”和“{}”:
'[{{[(){}]}}[]{}{{(())}}]'
'[{{}}[]{}{{(())}}]'
'[{}{}{{()}}]'
'[{}{{}}]'
'[{{}}]'
'[{}]'
''
如果最后字符串的长度为空 - 它是true
,如果不是 - 它是false
。
P.S。几个答案
因为它很慢,并且不关心对之间某些其他角色的可能性。
因为我是一名前端开发人员但遇到了同样的任务,所以也许这对某些人有用。 JS也是JVM lang =)
因为所有的JS开发人员都很疯狂,所以这就是原因。
答案 5 :(得分:1)
这是我自己的实现。我试图以最短的方式使它成为最短的方式:
public static boolean isBraceBalanced(String braces) {
Stack<Character> stack = new Stack<Character>();
for(char c : braces.toCharArray()) {
if(c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if((c == ')' && (stack.isEmpty() || stack.pop() != '(')) ||
(c == ']' && (stack.isEmpty() || stack.pop() != '[')) ||
(c == '}' && (stack.isEmpty() || stack.pop() != '{'))) {
return false;
}
}
return stack.isEmpty();
}
答案 6 :(得分:1)
类似于上面JAVA中的一个代码,但它需要添加一个else语句,以避免与大括号之外的字符进行堆栈比较:
else if(bracketPair.containsValue(strExpression.charAt(i)))
public boolean isBalanced(String strExpression){
Map<Character,Character> bracketPair = new HashMap<Character,Character>();
bracketPair.put('(', ')');
bracketPair.put('[', ']');
bracketPair.put('{', '}');
Stack<Character> stk = new Stack<Character>();
for(int i =0;i<strExpression.length();i++){
if(bracketPair.containsKey(strExpression.charAt(i)))
stk.push(strExpression.charAt(i));
else if(bracketPair.containsValue(strExpression.charAt(i)))
if(stk.isEmpty()||bracketPair.get(stk.pop())!=strExpression.charAt(i))
return false;
}
if(stk.isEmpty())
return true;
else
return false;
}
答案 7 :(得分:1)
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class BalancedParenthesisWithStack {
/*This is purely Java Stack based solutions without using additonal
data structure like array/Map */
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
/*Take list of String inputs (parenthesis expressions both valid and
invalid from console*/
List<String> inputs=new ArrayList<>();
while (sc.hasNext()) {
String input=sc.next();
inputs.add(input);
}
//For every input in above list display whether it is valid or
//invalid parenthesis expression
for(String input:inputs){
System.out.println("\nisBalancedParenthesis:"+isBalancedParenthesis
(input));
}
}
//This method identifies whether expression is valid parenthesis or not
public static boolean isBalancedParenthesis(String expression){
//sequence of opening parenthesis according to its precedence
//i.e. '[' has higher precedence than '{' or '('
String openingParenthesis="[{(";
//sequence of closing parenthesis according to its precedence
String closingParenthesis=")}]";
//Stack will be pushed on opening parenthesis and popped on closing.
Stack<Character> parenthesisStack=new Stack<>();
/*For expression to be valid :
CHECK :
1. it must start with opening parenthesis [()...
2. precedence of parenthesis should be proper (eg. "{[" invalid
"[{(" valid )
3. matching pair if( '(' => ')') i.e. [{()}(())] ->valid [{)]not
*/
if(closingParenthesis.contains
(((Character)expression.charAt(0)).toString())){
return false;
}else{
for(int i=0;i<expression.length();i++){
char ch= (Character)expression.charAt(i);
//if parenthesis is opening(ie any of '[','{','(') push on stack
if(openingParenthesis.contains(ch.toString())){
parenthesisStack.push(ch);
}else if(closingParenthesis.contains(ch.toString())){
//if parenthesis is closing (ie any of ']','}',')') pop stack
//depending upon check-3
if(parenthesisStack.peek()=='(' && (ch==')') ||
parenthesisStack.peek()=='{' && (ch=='}') ||
parenthesisStack.peek()=='[' && (ch==']')
){
parenthesisStack.pop();
}
}
}
return (parenthesisStack.isEmpty())? true : false;
}
}
答案 8 :(得分:1)
此代码适用于所有情况,包括其他字符,而不仅仅是括号
例如:
请输入输入
{ibrahim[k]}
真的
()[]{}[][]
真正
saddsd]
假
public class Solution {
private static Map<Character, Character> parenthesesMapLeft = new HashMap<>();
private static Map<Character, Character> parenthesesMapRight = new HashMap<>();
static {
parenthesesMapLeft.put('(', '(');
parenthesesMapRight.put(')', '(');
parenthesesMapLeft.put('[', '[');
parenthesesMapRight.put(']', '[');
parenthesesMapLeft.put('{', '{');
parenthesesMapRight.put('}', '{');
}
public static void main(String[] args) {
System.out.println("Please enter input");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
System.out.println(isBalanced(str));
}
public static boolean isBalanced(String str) {
boolean result = false;
if (str.length() < 2)
return false;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!parenthesesMapRight.containsKey(ch) && !parenthesesMapLeft.containsKey(ch)) {
continue;
}
if (parenthesesMapLeft.containsKey(ch)) {
stack.push(ch);
} else {
if (!stack.isEmpty() && stack.pop() == parenthesesMapRight.get(ch).charValue()) {
result = true;
} else {
return false;
}
}
}
if (!stack.isEmpty())
return result = false;
return result;
}
}
答案 9 :(得分:1)
这是我对这个问题的实现。此程序允许使用输入字符串的数字,字母和特殊字符,但在处理字符串时只需忽略它们。
CODE:
import java.util.Scanner;
import java.util.Stack;
public class StringCheck {
public static void main(String[] args) {
boolean flag =false;
Stack<Character> input = new Stack<Character>();
System.out.println("Enter your String to check:");
Scanner scanner = new Scanner(System.in);
String sinput = scanner.nextLine();
char[] c = new char[15];
c = sinput.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '{' || c[i] == '(' || c[i] == '[')
input.push(c[i]);
else if (c[i] == ']') {
if (input.pop() == '[') {
flag = true;
continue;
} else {
flag = false;
break;
}
} else if (c[i] == ')') {
if (input.pop() == '(') {
flag = true;
continue;
} else {
flag = false;
break;
}
} else if (c[i] == '}') {
if (input.pop() == '{') {
flag = true;
continue;
} else {
flag = false;
break;
}
}
}
if (flag == true)
System.out.println("Valid String");
else
System.out.println("Invalid String");
scanner.close();
}
}
答案 10 :(得分:1)
请试一试。
import java.util.Stack;
public class PatternMatcher {
static String[] patterns = { "{([])}", "{}[]()", "(}{}]]", "{()", "{}" };
static String openItems = "{([";
boolean isOpen(String sy) {
return openItems.contains(sy);
}
String getOpenSymbol(String byCloseSymbol) {
switch (byCloseSymbol) {
case "}":
return "{";
case "]":
return "[";
case ")":
return "(";
default:
return null;
}
}
boolean isValid(String pattern) {
if(pattern == null) {
return false;
}
Stack<String> stack = new Stack<String>();
char[] symbols = pattern.toCharArray();
if (symbols.length == 0 || symbols.length % 2 != 0) {
return false;
}
for (char c : symbols) {
String symbol = Character.toString(c);
if (isOpen(symbol)) {
stack.push(symbol);
} else {
String openSymbol = getOpenSymbol(symbol);
if (stack.isEmpty()
|| openSymbol == null
|| !openSymbol.equals(stack.pop())) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
PatternMatcher patternMatcher = new PatternMatcher();
for (String pattern : patterns) {
boolean valid = patternMatcher.isValid(pattern);
System.out.println(pattern + "\t" + valid);
}
}
}
答案 11 :(得分:1)
您正在推送i
- 索引 - 在堆栈上,并与ch
进行比较。你应该推送ch
。
答案 12 :(得分:0)
我们正在使用双端队列来轻松快速地找到平衡的字符串与否。在这个我们检查字符串包含等于关闭和打开这些'()'、'{}'和'[]'的数量。在这里,我们还检查了结束括号应该在开始括号之后。
/dev/stdout
答案 13 :(得分:0)
我称之为蛮力类型方法,我们将字符串中的每个 () 或 {} 或 [] 替换为“”,因此字符串的长度正在减少,如果字符串的长度没有改变,那么我只是在破坏否则循环,如果 String 的长度下降到 0,则表示 String 中的所有内容都是平衡的,否则不平衡。
public class Question{
public static void main(String[] args) {
String target="{ [ ( ) ] }",target2="( ) [ ] { }",target3="[ ( ) ] ( ( ) )",target4="( { [ )";
target=target.replaceAll(" ","");
target2=target2.replaceAll(" ", "");
target3=target3.replaceAll(" ", "");
target4=target4.replaceAll(" ", "");
System.out.println(CheckExp(target));
System.out.println(CheckExp(target2));
System.out.println(CheckExp(target3));
System.out.println(CheckExp(target4));
}
public static Boolean CheckExp(String target) {
boolean flag = false;
if (target.length() < 2 || target.length()%2!=0 ) {
return flag;
}
int first,last;
while(true) {
first=target.length();
target = target.replace("()", "");
target = target.replace("{}","");
target = target.replace("[]","");
last=target.length();
if(first==last)
break;
flag= target.length() == 0;
}
return flag;
}
}
答案 14 :(得分:0)
static void checkBalanceParan(String s){
Stack<Character>stk=new Stack<>();
int i=0;
int size=s.length();
while(i<size){
if(s.charAt(i)=='{'||s.charAt(i)=='('||s.charAt(i)=='['){
stk.push(s.charAt(i));
i++;
}
else if(s.charAt(i)=='}'&&!stk.empty()&&stk.peek()=='{'){
int x=stk.pop();
i++;
}else if(s.charAt(i)==')'&&!stk.empty()&&stk.peek()=='(')
{
int x=stk.pop();
i++;
}
else if(s.charAt(i)==']'&&!stk.empty()&&stk.peek()=='['){
int x=stk.pop();
i++;
}
else{
System.out.println("not Balanced");
return;
}
}
System.out.println("Balanced");}
答案 15 :(得分:0)
public static void main(String[] args) {
String exp = "{[()()]()}";
if(isBalanced(exp)){
System.out.println("Balanced");
}else{
System.out.println("Not Balanced");
}
}
public static boolean isBalanced(String exp){
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < exp.length(); i++) {
char a = exp.charAt(i);
char b =' ';
if(!stack.isEmpty()){
b = stack.peek();
}
if(a == '(' || a == '[' || a == '{'){
stack.push(a);
continue;
}
else if((b == '(' && a == ')') || (b == '[' && a == ']') || (b == '{' && a == '}')){
stack.pop();
continue;
}
else{
return false;
}
}
return stack.isEmpty();
}
在这种情况下,堆栈始终是最可取的数据结构,您可以考虑时间和空间复杂度来尝试。
答案 16 :(得分:0)
解决这个问题的方法略有不同,我已经观察到该问题的两个关键点。
因此,我将这些要点转换为易于实现且易于理解的格式。
例如:“ {}()[]”将为“ 1 -1 2 -2 3 -3”是有效的括号。 对于平衡括号,正数可以相邻,而负数应在堆栈顶部为正数。
下面是代码:
import java.util.Stack;
public class Main {
public static void main (String [] args)
{
String value = "()(){}{}{()}";
System.out.println(Main.balancedParanthesis(value));
}
public static boolean balancedParanthesis(String s) {
char[] charArray=s.toCharArray();
int[] integerArray=new int[charArray.length];
// creating braces with equivalent numeric values
for(int i=0;i<charArray.length;i++) {
if(charArray[i]=='{') {
integerArray[i]=1;
}
else if(charArray[i]=='}') {
integerArray[i]=-1;
}
else if(charArray[i]=='[') {
integerArray[i]=2;
}
else if(charArray[i]==']') {
integerArray[i]=-2;
}
else if(charArray[i]=='(') {
integerArray[i]=3;
}
else {
integerArray[i]=-3;
}
}
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<charArray.length;i++) {
if(stack.isEmpty()) {
if(integerArray[i]<0) {
stack.push(integerArray[i]);
break;
}
stack.push(integerArray[i]);
}
else{
if(integerArray[i]>0) {
stack.push(integerArray[i]);
}
else {
if(stack.peek()==-(integerArray[i])) {
stack.pop();
}
else {
break;
}
}
}
}
return stack.isEmpty();
}
}
答案 17 :(得分:0)
public class StackProb {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Boolean> list = new ArrayList<>();
while (sc.hasNextLine()) {
String s=sc.nextLine();
if(!s.isEmpty()) {
list.add(isBalanced(s));
//System.out.println(isBalanced(s));
}else {
sc.close();
break;
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + " ");
}
}
private static boolean isBalanced(String s) {
boolean res = false;
Stack<Character> stack = new Stack();
int countA = 0;
int countB = 0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='{' || s.charAt(i)=='(' || s.charAt(i)=='[') {
stack.push(s.charAt(i));
countA++;
}
if(s.charAt(i)=='}' || s.charAt(i)==')' || s.charAt(i)==']') {
stack.push(s.charAt(i));
countB++;
}
if(stack.firstElement()=='}' || stack.firstElement()==')' || stack.firstElement()==']') {
countB++;
}
}
if(countA==countB) {
return true;
}
return false;
}
}
答案 18 :(得分:0)
使用java.util.Stack
数据结构实现匹配括号的代码段-
//map for storing matching parenthesis pairs
private static final Map<Character, Character> matchingParenMap = new HashMap<>();
//set for storing opening parenthesis
private static final Set<Character> openingParenSet = new HashSet<>();
static {
matchingParenMap.put(')','(');
matchingParenMap.put(']','[');
matchingParenMap.put('}','{');
openingParenSet.addAll(matchingParenMap.values());
}
//check if parenthesis match
public static boolean hasMatchingParen(String input) {
try {
//stack to store opening parenthesis
Stack<Character> parenStack = new Stack<>();
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
//if an opening parenthesis then push to the stack
if(openingParenSet.contains(ch)) {
parenStack.push(ch);
}
//for closing parenthesis
if(matchingParenMap.containsKey(ch)) {
Character lastParen = parenStack.pop();
if(lastParen != matchingParenMap.get(ch)) {
return false;
}
}
}
//returns true if the stack is empty else false
return parenStack.isEmpty();
}
catch(StackOverflowException s) {}
catch(StackUnderflowException s1) {}
return false;
}
我已经解释了博客http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
上使用的代码段和算法答案 19 :(得分:0)
import java.util.Objects;
import java.util.Stack;
public class BalanceBrackets {
public static void main(String[] args) {
String input="(a{[d]}b)";
System.out.println(isBalance(input)); ;
}
private static boolean isBalance(String input) {
Stack <Character> stackFixLength = new Stack();
if(input == null || input.length() < 2) {
throw new IllegalArgumentException("in-valid arguments");
}
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
stackFixLength.push(input.charAt(i));
}
if (input.charAt(i) == ')' || input.charAt(i) == '}' || input.charAt(i) == ']') {
if(stackFixLength.empty()) return false;
char b = stackFixLength.pop();
if (input.charAt(i) == ')' && b == '(' || input.charAt(i) == '}' && b == '{' || input.charAt(i) == ']' && b == '[') {
continue;
} else {
return false;
}
}
}
return stackFixLength.isEmpty();
}
}
答案 20 :(得分:0)
package Stack;
import java.util.Stack;
public class BalancingParenthesis {
boolean isBalanced(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
stack.push(s.charAt(i)); // push to the stack
}
if (s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']') {
if (stack.isEmpty()) {
return false; // return false as there is nothing to match
}
Character top = stack.pop(); // to get the top element in the stack
if (top == '(' && s.charAt(i) != ')' || top == '{' && s.charAt(i) != '}'
|| top == '[' && s.charAt(i) != ']') {
return false;
}
}
}
if (stack.isEmpty()) {
return true; // check if every symbol is matched
}
return false; // if some symbols were unmatched
}
public static void main(String[] args) {
BalancingParenthesis obj = new BalancingParenthesis();
System.out.println(obj.isBalanced("()[]{}[][]"));
}
}
// Time Complexity : O(n)
答案 21 :(得分:0)
///check Parenthesis
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(map.containsKey(c)){
stack.push(c);
} else if(!stack.empty() && map.get(stack.peek())==c){
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
答案 22 :(得分:0)
使用开关盒以提高可读性并处理其他情况:
import java.util.Scanner;
import java.util.Stack;
public class JavaStack
{
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.next();
System.out.println(isStringBalanced(input));
}
scanner.close();
}
private static boolean isStringBalanced(String testString)
{
Stack<Character> stack = new Stack<Character>();
for (char c : testString.toCharArray()) {
switch (c) {
case '[':
case '(':
case '{':
stack.push(c);
break;
case ']':
if (stack.isEmpty() || stack.pop() != '[') {
return false;
}
break;
case ')':
if (stack.isEmpty() || stack.pop() != '(') {
return false;
}
break;
case '}':
if (stack.isEmpty() || stack.pop() != '{') {
return false;
}
break;
default:
break;
}
}
// stack has to be empty, if not, the balance was wrong
return stack.empty();
}
}
答案 23 :(得分:0)
最新帖子。
package com.prac.stack;
public class BalanceBrackets {
public static void main(String[] args) {
String str = "{()}[]";
char a[] = str.toCharArray();
System.out.println(check(a));
}
static boolean check(char[] t) {
Stackk st = new Stackk();
for (int i = 0; i < t.length; i++) {
if (t[i] == '{' || t[i] == '(' || t[i] == '[') {
st.push(t[i]);
}
if (t[i] == '}' || t[i] == ')' || t[i] == ']') {
if (st.isEmpty()) {
return false;
} else if (!isMatching(st.pop(), t[i])) {
return false;
}
}
}
if (st.isEmpty()) {
return true;
} else {
return false;
}
}
static boolean isMatching(char a, char b) {
if (a == '(' && b == ')') {
return true;
} else if (a == '{' && b == '}') {
return true;
} else if (a == '[' && b == ']') {
return true;
} else {
return false;
}
}
}
答案 24 :(得分:0)
Hashmap的替代方法和有效方法是使用Deque:
public boolean isValid(String s)
{
if(s == null || s.length() == 0)
return true;
Deque<Character> stack = new ArrayDeque<Character>();
for(char c : s.toCharArray())
{
if(c == '{')
stack.addFirst('}');
else if(c == '(')
stack.addFirst(')');
else if(c == '[')
stack .addFirst(']');
else if(stack.isEmpty() || c != stack.removeFirst())
return false;
}
return stack.isEmpty();
}
答案 25 :(得分:0)
考虑字符串仅由'('')''{''}''['']'组成。这是一种根据方程是否平衡来返回true或false的代码方法。
private static boolean checkEquation(String input) {
List<Character> charList = new ArrayList<Character>();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
charList.add(input.charAt(i));
} else if ((input.charAt(i) == ')' && charList.get(charList.size() - 1) == '(')
|| (input.charAt(i) == '}' && charList.get(charList.size() - 1) == '{')
|| (input.charAt(i) == ']' && charList.get(charList.size() - 1) == '[')) {
charList.remove(charList.size() - 1);
} else
return false;
}
if(charList.isEmpty())
return true;
else
return false;
}
答案 26 :(得分:0)
public void validateExpression(){
if(!str.isEmpty() && str != null){
if( !str.trim().equals("(") && !str.trim().equals(")")){
char[] chars = str.toCharArray();
for(char c: chars){
if(!Character.isLetterOrDigit(c) && c == '(' || c == ')') {
charList.add(c);
}
}
for(Character ele: charList){
if(operatorMap.get(ele) != null && operatorMap.get(ele) != 0){
operatorMap.put(ele,operatorMap.get(ele)+1);
}else{
operatorMap.put(ele,1);
}
}
for(Map.Entry<Character, Integer> ele: operatorMap.entrySet()){
System.out.println(String.format("Brace Type \"%s\" and count is \"%d\" ", ele.getKey(),ele.getValue()));
}
if(operatorMap.get('(') == operatorMap.get(')')){
System.out.println("**** Valid Expression ****");
}else{
System.out.println("**** Invalid Expression ****");
}
}else{
System.out.println("**** Incomplete expression to validate ****");
}
}else{
System.out.println("**** Expression is empty or null ****");
}
}
答案 27 :(得分:0)
package com.me.hr;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;
public class Paranthesis {
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.next();
Paranthesis obj = new Paranthesis();
System.out.println(obj.isEven(input));
} // Complete the code }
sc.close();
}
boolean isEven(String token) {
HashMap<Character, Character> paranthesisMap = new HashMap<Character, Character>();
paranthesisMap.put('{', '}');
paranthesisMap.put('[', ']');
paranthesisMap.put('(', ')');
// List<Character> closingThesis = Arrays.asList('}',']',')');
char[] chars = token.toCharArray();
Stack<Character> stack = new Stack<Character>();
for (char ch : chars) {
boolean push = true;
// Not Allow closing prthese first
if (stack.isEmpty() && paranthesisMap.values().contains(ch))
return false;
// Pop Out Matching closing prthese
if (!stack.isEmpty() && paranthesisMap.values().contains(ch)) {
char peek = stack.peek();
if (paranthesisMap.get(peek).equals(ch)) {
stack.pop();
push = false;
} else {
// Otherwise not matching
return false;
}
}
if (push)
stack.push(ch);
}
if (stack.isEmpty())
return true;
return false;
}
}
答案 28 :(得分:0)
改进的方法,来自@Smartoop。
public boolean balancedParenthensies(String str) {
List<Character> leftKeys = Arrays.asList('{', '(', '<', '[');
List<Character> rightKeys = Arrays.asList('}', ')', '>', ']');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (leftKeys.contains(c)) {
stack.push(c);
} else if (rightKeys.contains(c)) {
int index = rightKeys.indexOf(c);
if (stack.isEmpty() || stack.pop() != leftKeys.get(index)) {
return false;
}
}
}
return stack.isEmpty();
}
答案 29 :(得分:0)
使用节点参考我们可以轻松检查
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CloseBracketsBalance {
private static final Map<String, String> closeBracket= new HashMap<>();
private static final List<String> allBrac = new ArrayList<>();
static {
allBrac.add("[");
allBrac.add("]");
allBrac.add("{");
allBrac.add("}");
allBrac.add("(");
allBrac.add(")");
closeBracket.put("]", "[");
closeBracket.put("}", "{");
closeBracket.put(")", "(");
}
public static void main(String[] args) {
System.out.println(checkSheetIsbalance("[{}({[]{}(dsfd)})]")); // return true
System.out.println(checkSheetIsbalance("[{}({[]{}(dsfd}))]")); // return false
}
public static boolean checkSheetIsbalance(String c) {
char[] charArr = c.toCharArray();
Node node = null;
for(int i=0,j=charArr.length;i<j;i++) {
String ch = charArr[i]+"";
if(!allBrac.contains(ch)) {
continue;
}
if(closeBracket.containsKey(ch)) {
// node close bracket
if(node == null) {
return false;
}
if(!(node.nodeElement).equals(closeBracket.get(ch))) {
return false;
}
node = node.parent;
} else {
//make node for open bracket
node = new Node(ch, node);
}
}
if(node != null) {
return false;
}
return true;
}
}
class Node {
public String nodeElement;
public Node parent;
public Node(String el, Node p) {
this.nodeElement = el;
this.parent = p;
}
}
答案 30 :(得分:0)
这是守则。我已经在Hacker Rank上测试了所有可能的测试用例。
static String isBalanced(String input){
In sdk/build-tools folder i have
22.0.1
24.0.0
24.0.1
25.0.1
26.0.0
答案 31 :(得分:0)
请尝试这个我检查过。它工作正常
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class CloseBrackets {
private static Map<Character, Character> leftChar = new HashMap<>();
private static Map<Character, Character> rightChar = new HashMap<>();
static {
leftChar.put('(', '(');
rightChar.put(')', '(');
leftChar.put('[', '[');
rightChar.put(']', '[');
leftChar.put('{', '{');
rightChar.put('}', '{');
}
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String st = bf.readLine();
System.out.println(isBalanced(st));
}
public static boolean isBalanced(String str) {
boolean result = false;
if (str.length() < 2)
return false;
Stack<Character> stack = new Stack<>();
/* For Example I gave input
* str = "{()[]}"
*/
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!rightChar.containsKey(ch) && !leftChar.containsKey(ch)) {
continue;
}
// Left bracket only add to stack. Other wise it will goes to else case
// For both above input how value added in stack
// "{(" after close bracket go to else case
if (leftChar.containsKey(ch)) {
stack.push(ch);
} else {
if (!stack.isEmpty()) {
// For both input how it performs
// 3rd character is close bracket so it will pop . pop value is "(" and map value for ")" key will "(" . So both are same .
// it will return true.
// now stack will contain only "{" , and travers to next up to end.
if (stack.pop() == rightChar.get(ch).charValue() || stack.isEmpty()) {
result = true;
} else {
return false;
}
} else {
return false;
}
}
}
if (!stack.isEmpty())
return result = false;
return result;
}
}
答案 32 :(得分:0)
这可以使用。通过所有测试。
static String isBalanced(String s) {
if(null == s){
return "";
}
Stack<Character> bracketStack = new Stack<>();
int length = s.length();
if(length < 2 || length > 1000){
return "NO";
}
for(int i = 0; i < length; i++){
Character c= s.charAt(i);
if(c == '(' || c == '{' || c == '[' ){
bracketStack.push(c);
} else {
if(!bracketStack.isEmpty()){
char cPop = bracketStack.pop();
if(c == ']' && cPop!= '['){
return "NO";
}
if(c == ')' && cPop!= '('){
return "NO";
}
if(c == '}' && cPop!= '{'){
return "NO";
}
} else{
return "NO";
}
}
}
if(bracketStack.isEmpty()){
return "YES";
} else {
return "NO";
}
}
答案 33 :(得分:0)
这个怎么样,它使用堆栈加计数器检查的概念:
import java.util.*;
class Solution{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
Stack<Character> stk = new Stack<Character>();
char[] chr = input.toCharArray();
int ctrl = 0, ctrr = 0;
if(input.length()==0){
System.out.println("true");
}
for(int i=0; i<input.length(); i++){
if(chr[i]=='{'||chr[i]=='('||chr[i]=='['){
ctrl++;
stk.push(chr[i]);
//System.out.println(stk);
}
}
for(int i=0; i<input.length(); i++){
if(chr[i]=='}'||chr[i]==')'||chr[i]==']'){
ctrr++;
if(!stk.isEmpty())
stk.pop();
//System.out.println(stk);
}
}
//System.out.println(stk);
if(stk.isEmpty()&&ctrl==ctrr)
System.out.println("true");
else
System.out.println("false");
}
}
}
答案 34 :(得分:0)
sd(x, na.rm=T)
简化并使其易读。 仅使用一个地图和最小条件来获得所需结果。
答案 35 :(得分:0)
import java.util.Stack;
public class StackParenthesisImplementation {
public static void main(String[] args) {
String Parenthesis = "[({})]";
char[] charParenthesis = Parenthesis.toCharArray();
boolean evalParanthesisValue = evalParanthesis(charParenthesis);
if(evalParanthesisValue == true)
System.out.println("Brackets are good");
else
System.out.println("Brackets are not good");
}
static boolean evalParanthesis(char[] brackets)
{
boolean IsBracesOk = false;
boolean PairCount = false;
Stack<Character> stack = new Stack<Character>();
for(char brace : brackets)
{
if(brace == '(' || brace == '{' || brace == '['){
stack.push(brace);
PairCount = false;
}
else if(!stack.isEmpty())
{
if(brace == ')' || brace == '}' || brace == ']')
{
char CharPop = stack.pop();
if((brace == ')' && CharPop == '('))
{
IsBracesOk = true; PairCount = true;
}
else if((brace == '}') && (CharPop == '{'))
{
IsBracesOk = true; PairCount = true;
}
else if((brace == ']') && (CharPop == '['))
{
IsBracesOk = true; PairCount = true;
}
else
{
IsBracesOk = false;
PairCount = false;
break;
}
}
}
}
if(PairCount == false)
return IsBracesOk = false;
else
return IsBracesOk = true;
}
}
答案 36 :(得分:-1)
**// balanced parentheses problem (By fabboys)**
#include <iostream>
#include <string.h>
using namespace std;
class Stack{
char *arr;
int size;
int top;
public:
Stack(int s)
{
size = s;
arr = new char[size];
top = -1;
}
bool isEmpty()
{
if(top == -1)
return true;
else
return false;
}
bool isFull()
{
if(top == size-1)
return true;
else
return false;
}
void push(char n)
{
if(isFull() == false)
{
top++;
arr[top] = n;
}
}
char pop()
{
if(isEmpty() == false)
{
char x = arr[top];
top--;
return x;
}
else
return -1;
}
char Top()
{
if(isEmpty() == false)
{
return arr[top];
}
else
return -1;
}
Stack{
delete []arr;
}
};
int main()
{
int size=0;
string LineCode;
cout<<"Enter a String : ";
cin >> LineCode;
size = LineCode.length();
Stack s1(size);
char compare;
for(int i=0;i<=size;i++)
{
if(LineCode[i]=='(' || LineCode[i] == '{' || LineCode[i] =='[')
s1.push(LineCode[i]);
else if(LineCode[i]==']')
{
if(s1.isEmpty()==false){
compare = s1.pop();
if(compare == 91){}
else
{
cout<<" Error Founded";
return 0;}
}
else
{
cout<<" Error Founded";
return 0;
}
} else if(LineCode[i] == ')')
{
if(s1.isEmpty() == false)
{
compare = s1.pop();
if(compare == 40){}
else{
cout<<" Error Founded";
return 0;
}
}else
{
cout<<"Error Founded";
return 0;
}
}else if(LineCode[i] == '}')
{
if(s1.isEmpty() == false)
{
compare = s1.pop();
if(compare == 123){}
else{
cout<<" Error Founded";
return 0;
}
}else
{
cout<<" Error Founded";
return 0;
}
}
}
if(s1.isEmpty()==true)
{
cout<<"No Error in Program:\n";
}
else
{
cout<<" Error Founded";
}
return 0;
}