首页 > 其他 > 详细

[LeetCode] Valid Parentheses

时间:2015-11-06 19:38:38      阅读:243      评论:0      收藏:0      [点我收藏+]

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Subscribe to see which companies asked this question

解题思路

借助栈来实现:

  • 如果为左括号则入栈;
  • 如果为右括号, 若:
    • 栈顶为与之匹配的左括号,则出栈。
    • 否则,返回false。
  • 最后,返回stack.empty()

实现代码

C++:

// Runtime: 0 ms
class Solution {
public:
    bool isValid(string s) {
        unordered_map<char, char> mymap = {{‘(‘, ‘)‘}, {‘[‘, ‘]‘}, {‘{‘, ‘}‘}};
        stack<char> mystack;
        for (int i = 0; i < s.length(); i++)
        {
            if (s[i] == ‘(‘ || s[i] == ‘[‘ || s[i] == ‘{‘)
            {
                mystack.push(s[i]);
            }
            else if (!mystack.empty() && (mymap[mystack.top()] == s[i]))
            {
                mystack.pop();
            }
            else
            {
                return false;
            }
        }

        return mystack.empty();
    }
};

Java:

// Runtime: 2 ms
public class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<Character, Character>();
        Stack<Character> stack = new Stack<Character>();
        map.put(‘(‘, ‘)‘);
        map.put(‘[‘, ‘]‘);
        map.put(‘{‘, ‘}‘);
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                stack.push(s.charAt(i));
            }
            else if (!stack.empty() && map.get(stack.peek()).equals(s.charAt(i))) {
                stack.pop();
            }
            else {
                return false;
            }
        }

        return stack.empty();
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Valid Parentheses

原文:http://blog.csdn.net/foreverling/article/details/49685177

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!