Parenthesis/Brackets Matching using Stack algorith

2019-01-06 09:35发布

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not matching it should return false, eg:

{}
({}(
){})
(()

and so on. Can you please check this code? Thanks in advance.

public static boolean isParenthesisMatch(String str) {
    Stack<Character> stack = new Stack<Character>();

    char c;
    for(int i=0; i < str.length(); i++) {
        c = str.charAt(i);

        if(c == '{')
            return false;

        if(c == '(')
            stack.push(c);

        if(c == '{') {
            stack.push(c);
            if(c == '}')
                if(stack.empty())
                    return false;
                else if(stack.peek() == '{')
                    stack.pop();
        }
        else if(c == ')')
            if(stack.empty())
                return false;
            else if(stack.peek() == '(')
                    stack.pop();
                else
                    return false;
        }
        return stack.empty();
}

public static void main(String[] args) {        
    String str = "({})";
    System.out.println(Weekly12.parenthesisOtherMatching(str)); 
}

25条回答
Juvenile、少年°
2楼-- · 2019-01-06 10:05
import java.util.Stack;

class Demo
{

    char c;

    public  boolean checkParan(String word)
    {
        Stack<Character> sta = new Stack<Character>();
        for(int i=0;i<word.length();i++)
        {
           c=word.charAt(i);


          if(c=='(')
          {
              sta.push(c);
              System.out.println("( Pushed into the stack");

          }
          else if(c=='{')
          {
              sta.push(c);
              System.out.println("( Pushed into the stack");
          }
          else if(c==')')
          {
              if(sta.empty())
              {
                  System.out.println("Stack is Empty");
                  return false;
              }
              else if(sta.peek()=='(')
              {

                  sta.pop();
                  System.out.println(" ) is poped from the Stack");
              }
              else if(sta.peek()=='(' && sta.empty())
              {
                  System.out.println("Stack is Empty");
                  return false;
              }
          }
          else if(c=='}')
          {
              if(sta.empty())
              {
               System.out.println("Stack is Empty");
              return false;
              }
              else if(sta.peek()=='{')
              {
                  sta.pop();
                  System.out.println(" } is poped from the Stack");
              }

          }

          else if(c=='(')
          {
              if(sta.empty())
              {
                 System.out.println("Stack is empty only ( parenthesis in Stack ");  
              }
          }


        }
    // System.out.print("The top element is : "+sta.peek());
    return sta.empty();
    } 





}

public class ParaenthesisChehck {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       Demo d1= new Demo();
     //  d1.checkParan(" ");
      // d1.checkParan("{}");
       //d1.checkParan("()");
       //d1.checkParan("{()}");
     // d1.checkParan("{123}");
       d1.checkParan("{{{}}");





    }

}
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-06 10:05

in java you don't want to compare the string or char by == signs. you would use equals method. equalsIgnoreCase or something of the like. if you use == it must point to the same memory location. In the method below I attempted to use ints to get around this. using ints here from the string index since every opening brace has a closing brace. I wanted to use location match instead of a comparison match. But i think with this you have to be intentional in where you place the characters of the string. Lets also consider that Yes = true and No = false for simplicity. This answer assumes that you passed an array of strings to inspect and required an array of if yes (they matched) or No (they didn't)

import java.util.Stack; 

    public static void main(String[] args) {

    //String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","{}","}]{}","{[)]()}"};
    // Example: "()" is balanced
    // Example: "{ ]" is not balanced.
    // Examples: "()[]{}" is balanced.
    // "{([])}" is balanced
    // "{([)]}" is _not_ balanced

    String[] arrayOfBraces  = new String[]{"{[]}","([{}])","{}{()}","()[]{}","}]{}","{[)]()}","{[)]()}","{([)]}"};
    String[] answers        = new String[arrayOfBraces.length];     
    String openers          = "([{";
    String closers          = ")]}";
    String stringToInspect  = ""; 
    Stack<String> stack     = new Stack<String>();


    for (int i = 0; i < arrayOfBraces.length; i++) {

        stringToInspect = arrayOfBraces[i];
        for (int j = 0; j < stringToInspect.length(); j++) {            
            if(stack.isEmpty()){
                if (openers.indexOf(stringToInspect.charAt(j))>=0) {
                    stack.push(""+stringToInspect.charAt(j));   
                }
                else{
                    answers[i]= "NO";
                    j=stringToInspect.length();
                }                   
            }
            else if(openers.indexOf(stringToInspect.charAt(j))>=0){
                stack.push(""+stringToInspect.charAt(j));   
            }
            else{
                String comparator = stack.pop();
                int compLoc = openers.indexOf(comparator);
                int thisLoc = closers.indexOf(stringToInspect.charAt(j));

                if (compLoc != thisLoc) {
                    answers[i]= "NO";
                    j=stringToInspect.length();                     
                }
                else{
                    if(stack.empty() && (j== stringToInspect.length()-1)){
                        answers[i]= "YES";
                    }
                }
            }
        }
    }

    System.out.println(answers.length);         
    for (int j = 0; j < answers.length; j++) {
        System.out.println(answers[j]);
    }       
}
查看更多
我只想做你的唯一
4楼-- · 2019-01-06 10:06

I tried this using javascript below is the result.

function bracesChecker(str) {
  if(!str) {
    return true;
  }
  var openingBraces = ['{', '[', '('];
  var closingBraces = ['}', ']', ')'];
  var stack = [];
  var openIndex;
  var closeIndex;
  //check for opening Braces in the val
  for (var i = 0, len = str.length; i < len; i++) {
    openIndex = openingBraces.indexOf(str[i]);
    closeIndex = closingBraces.indexOf(str[i]);
    if(openIndex !== -1) {
      stack.push(str[i]);
    }  
    if(closeIndex !== -1) {
      if(openingBraces[closeIndex] === stack[stack.length-1]) { 
        stack.pop();
      } else {
        return false;
      }
    }
  }
  if(stack.length === 0) {
    return true;
  } else {
    return false;
  }
}
var testStrings = [
  '', 
  'test', 
  '{{[][]()()}()}[]()', 
  '{test{[test]}}', 
  '{test{[test]}', 
  '{test{(yo)[test]}}', 
  'test{[test]}}', 
  'te()s[]t{[test]}', 
  'te()s[]t{[test'
];

testStrings.forEach(val => console.log(`${val} => ${bracesChecker(val)}`));
查看更多
【Aperson】
5楼-- · 2019-01-06 10:07
public String checkString(String value) {
    Stack<Character> stack = new Stack<>();
    char topStackChar = 0;
    for (int i = 0; i < value.length(); i++) {
        if (!stack.isEmpty()) {
            topStackChar = stack.peek();
        }
        stack.push(value.charAt(i));
        if (!stack.isEmpty() && stack.size() > 1) {
            if ((topStackChar == '[' && stack.peek() == ']') ||
                    (topStackChar == '{' && stack.peek() == '}') ||
                    (topStackChar == '(' && stack.peek() == ')')) {
                stack.pop();
                stack.pop();
            }
        }
    }
    return stack.isEmpty() ? "YES" : "NO";
}
查看更多
Animai°情兽
6楼-- · 2019-01-06 10:07
  Check balanced parenthesis or brackets with stack-- 
  var excp = "{{()}[{a+b+b}][{(c+d){}}][]}";
   var stk = [];   
   function bracket_balance(){
      for(var i=0;i<excp.length;i++){
          if(excp[i]=='[' || excp[i]=='(' || excp[i]=='{'){
             stk.push(excp[i]);
          }else if(excp[i]== ']' && stk.pop() != '['){
             return false;
          }else if(excp[i]== '}' && stk.pop() != '{'){

            return false;
          }else if(excp[i]== ')' && stk.pop() != '('){

            return false;
          }
      }

      return true;
   }

  console.log(bracket_balance());
  //Parenthesis are balance then return true else false
查看更多
趁早两清
7楼-- · 2019-01-06 10:08

Optimized implementation using Stacks and Switch statement:

public class JavaStack {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

      Stack<Character> s = new Stack<Character>();

    while (sc.hasNext()) {
        String input = sc.next();

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            switch (c) {

                case '(':
                    s.push(c); break;
                case '[':
                    s.push(c); break;
                case '{':
                    s.push(c); break;
                case ')':
                    if (!s.isEmpty() && s.peek().equals('(')) {
                        s.pop();
                    } else {
                        s.push(c);
                    } break;
                case ']':
                    if (!s.isEmpty() && s.peek().equals('[')) {
                        s.pop();
                    } else {
                        s.push(c);
                    } break;
                case '}':
                    if (!s.isEmpty() && s.peek().equals('{')) {
                        s.pop();
                    } else {
                        s.push(c);
                    } break;

                default:
                    s.push('x'); break;

            }

        }
        if (s.empty()) {
            System.out.println("true");
        } else {
            System.out.println("false");
            s.clear();
        }
    }
} }

Cheers !

查看更多
登录 后发表回答