LeetCode-20. Valid Parentheses

xiaoxiao2021-03-01  12

https://leetcode.com/problems/valid-parentheses/description/

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()" Output: true

Example 2:

Input: "()[]{}" Output: true

Example 3:

Input: "(]" Output: false

Example 4:

Input: "([)]" Output: false

Example 5:

Input: "{[]}" Output: true

题解:

class Solution { public: bool isValid(string s) { stack<char> st; int n = s.length(); if (n == 0) { return true; } int i = 0; st.push(s[i++]); while (i < n) { if (s[i] == '(' || s[i] == '{' || s[i] == '[') { st.push(s[i++]); } else if (s[i] == ')' || s[i] == '}' || s[i] == ']') { if (st.empty() == true) { return false; } char tmp = st.top(); st.pop(); if (tmp == '(' && s[i] == ')') { i++; continue; } if (tmp == '[' && s[i] == ']') { i++; continue; } if (tmp == '{' && s[i] == '}') { i++; continue; } return false; } } return st.empty(); } };

 

转载请注明原文地址: https://www.6miu.com/read-3650035.html

最新回复(0)