项目作者: eMahtab

项目描述 :
Balanced Brackets
高级语言:
项目地址: git://github.com/eMahtab/balanced-brackets.git
创建时间: 2019-12-04T12:49:25Z
项目社区:https://github.com/eMahtab/balanced-brackets

开源协议:

下载


Balanced Brackets (Valid Parentheses)

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

An input string is valid if: Open brackets are closed by the same type of brackets and in the correct order.

Note that an empty string is also considered valid.

  1. Example 1:
  2. Input: "()"
  3. Output: true
  4. Example 2:
  5. Input: "()[]{}"
  6. Output: true
  7. Example 3:
  8. Input: "(]"
  9. Output: false

Implementation

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Stack;
  4. public class App {
  5. public static void main(String[] args) {
  6. String s = ")[]}";
  7. System.out.println(isValid(s));
  8. }
  9. public static boolean isValid(String s) {
  10. Stack<String> stack = new Stack<String>();
  11. Map<String,String> map = new HashMap<String,String>();
  12. map.put("]", "["); map.put(")", "("); map.put("}", "{");
  13. for(int i = 0; i < s.length(); i++) {
  14. String st = Character.toString(s.charAt(i));
  15. if(!map.containsKey(st)) {
  16. stack.push(st);
  17. } else {
  18. if(stack.isEmpty()) {
  19. return false;
  20. } else {
  21. String peek = stack.peek();
  22. if(peek.equals(map.get(st))) {
  23. stack.pop();
  24. } else {
  25. return false;
  26. }
  27. }
  28. }
  29. }
  30. return stack.isEmpty();
  31. }
  32. }