[leetcode] 20. Valid Parentheses (easy)

原题链接

匹配括号
思路:
用栈,遍历过程中,匹配的成对出栈;结束后,栈空则对,栈非空则错。
Runtime: 4 ms, faster than 99.94% of Java

class Solution {
	public boolean isValid(String s) {
		Stack<Character> sta = new Stack<Character>();

		for (int i = 0; i < s.length(); i++) {
			char temp = s.charAt(i);
			if (temp == '[' || temp == '(' || temp == '{') {
			sta.push(temp);
			} else {
			if (sta.isEmpty())
				return false;
			char top = ' ';
			if (temp == ']')
				top = '[';
			if (temp == ')')
				top = '(';
			if (temp == '}')
				top = '{';
			if (top == sta.peek())
				sta.pop();
			else
				return false;
			}
		}
		return sta.isEmpty() ? true : false;
	}

	}
posted @ 2018-11-13 11:47  Ruohua3kou  阅读(91)  评论(0编辑  收藏  举报