---
title: "Valid Parentheses "
author: "plan454"
date: "2015-03-05T22:33:52Z"
tags: []
categories: ["非技术"]
slug: "valid-parentheses"
draft: false
lastmod: "2015-03-05T22:33:52Z"
id: 2189218
url: "https://plan454.iteye.com/blog/2189218"
---

Given a string containing just the characters '(', ')', '{', '}', '', determine if the input string is valid.

The brackets must close in the correct order, "()" and "(){}" are all valid but "(]" and "(" are not.

这是一道匹配题，最简单的方式就是用栈来做了，JAVA中有Strack类，所以直接用就可以了。

```java
public boolean isValid(String s) {
        boolean result = false;
        List<Character> ls = new ArrayList<Character>();
        if(s == null || s.length()<2){
        	return false;
        }
        
        char[] chs = {'(',')','[',']','{','}'};
        for(char c : chs){
        	ls.add(c);
        }
        Stack<Character> st = new Stack<Character>();
        for(int i = 0 ;i<s.length();i++){
        	if(ls.contains(s.charAt(i))){
        			if(st.isEmpty()){
        				st.push(s.charAt(i));
        			}else{
        				/*System.out.println((char)st.peek());
        				System.out.println(s.charAt(i));
        				
        				System.out.println((char)st.peek()+s.charAt(i));*/
        				if((char)st.peek()+s.charAt(i) == 81 || (char)st.peek()+s.charAt(i) == 248 ||(char)st.peek()+s.charAt(i) == 184){
        					st.pop();
        				}else{
        					st.push(s.charAt(i));
        				}
        			}
        		
        	}
        }
        if(st.isEmpty()){
        	result = true;
        }else{
        	result = false;
        }
        
        
        return result;
    }
```