leetcode_Valid Parentheses

描述:

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.

思路:

很简单的字符串匹配问题,直接用栈就可以实现,为使程序更加高效,当要匹配的字符种类比较多的时候可以考虑用HashMap来保存匹配对

代码:

用if else来比较匹配对

public  boolean isValid(String s) {
        if(s==null||s.length()==0)
            return true;
        Stack<Character> st=new Stack<Character>();
        char ch;
        int len=s.length();
        for(int i=0;i<len;i++)
        {
            ch=s.charAt(i);
            if(!st.empty())
            {
                if(ch==')'&&st.peek()=='(')
                {
                    st.pop();
                }else if(ch==']'&&st.peek()=='[')
                {
                    st.pop();
                }
                else if(ch=='}'&&st.peek()=='{')
                {
                    st.pop();
                }else
                    st.push(ch);
            }else
                st.push(ch);

        }
        if(!st.empty())
            return false;
        return true;

    }

用HashMap来保存匹配对

public  boolean isValid(String s) {
		if (s == null || s.length() == 0)
			return true;
		Stack<Character> st = new Stack<Character>();
		Map<Character, Character> map = new HashMap<Character, Character>();
		map.put('(', ')');
		map.put('{', '}');
		map.put('[', ']');
		int len=s.length();
		for (int i = 0; i < len; i++) {
			if (!st.empty()&&map.containsKey(st.peek())&&s.charAt(i) == map.get(st.peek())) {
				st.pop();
			}else
				st.push(s.charAt(i));
		}
		return st.empty();
	}
时间: 2024-12-06 21:40:34

leetcode_Valid Parentheses的相关文章

leetcode22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 这个问题解的个

Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" class S

#22 Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 本题是括号匹配

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

LeetCode 241. Different Ways to Add Parentheses

241. Different Ways to Add Parentheses Add to List Description Submission Solutions Total Accepted: 38849 Total Submissions: 92740 Difficulty: Medium Contributors: Admin Given a string of numbers and operators, return all possible results from comput

leetcode 20 Valid Parentheses

class Solution { public: bool isValid(string s) { stack<char> parentheses; for (int i = 0; i < s.size(); ++i) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]); else { if (parentheses.empty()) return false; if (s[i] == ')' &

22. Generate Parentheses——本质:树,DFS求解可能的path

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] cla

32. Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is &

241. Different Ways to Add Parentheses

241. Different Ways to Add Parentheses https://leetcode.com/problems/different-ways-to-add-parentheses/ 思路就是:首先找到以运算符为根节点,分别计算左子串和右子串的所有结果的集合,然后依次进行组合计算.参考博客http://www.cnblogs.com/ganganloveu/p/4681439.html. 自己的思路错了,直接用两边只用了一个整数去接收左右子串的计算值!! #include