20. 有效的括号/32.最长有效括号

版权声明:只要梦想一天,只要梦想存在一天,就可以改变自己的处境。 https://blog.csdn.net/dongyanwen6036/article/details/85263332
20. 有效的括号

示例 1:

输入: “()”
输出: true

示例 2:

输入: “()[]{}”
输出: true

示例 3:

输入: “(]”
输出: false

示例 4:

输入: “([)]”
输出: false

示例 5:

输入: “{[]}”
输出: true

//我的想法是利用一个栈,最后栈为空就true
public:
	bool isValid(string s) {
		if (s.empty())return true;
		stack<char>St;
		for (int i = 0; i < s.size(); i++)
		{
			if (St.empty())
			{
				St.push(s[i]);
				continue;
			}
			char c = St.top();
			if (c == '('&&s[i] == ')')
			{
				St.pop();
				continue;
			}
			if (c == '['&&s[i] == ']')
			{
				St.pop();
				continue;
			}
			if (c == '{'&&s[i] == '}')
			{
				St.pop();
				continue;
			}
			St.push(s[i]);
		}
		if (St.empty())return true;
		return false;
	}
};
32.最长有效括号

思路[1]是采用栈和动态规划:

  1. 定义start变量记录合法括号串的起始位置
  2. 遍历字符串
  3. 如果遇到(,则将当前下标压入栈
  4. 如果遇到),则有两种情况:
    • 如果当前栈为空,则将下一个坐标位置记录到start
    • 如果当前栈不为空,则将栈顶元素取出
      • 若此时栈为空,最长值=max(最长值, 当前下标 - start + 1)
      • 否则最长值=max(最长值, 当前下标 - 栈顶元素值)
class Solution {
 public:
	 int longestValidParentheses(string s) {
		 int res = 0, start = 0;
		 stack<int>T;
		 for (int i = 0; i < s.size(); i++)
		 {
			 if (s[i] == '(')T.push(i);
			 else if (s[i] == ')')
			 {
				 if (T.empty())start = i + 1;
				 else
				 {
					 T.pop();
					 res = T.empty() ? max(res,i-start+1) : max(res,i-T.top());
				 }
			 }
		 }
		 return res;
	 }
 };

[1]https://yq.aliyun.com/articles/355654

猜你喜欢

转载自blog.csdn.net/dongyanwen6036/article/details/85263332