当前位置:网站首页>[LeetCode]20. Valid parentheses thirty-six

[LeetCode]20. Valid parentheses thirty-six

2022-06-13 00:12:00 PowerDon

Given one only includes ‘(’,’)’,’{’,’}’,’[’,’]’  String , Determines whether the string is valid .

Valid string needs to meet :

Opening parentheses must be closed with closing parentheses of the same type .
The left parenthesis must be closed in the correct order .
Note that an empty string can be considered a valid string .

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

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/valid-parentheses
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

public class Solution {
    
    public bool IsValid(string s) {
    
        if(s.Length == 0){
    
            return true;
        }
        if(Array.IndexOf(new char[]{
    ')',']','}'}, s[0]) >= 0){
    
            return false;
        }
        Stack map = new Stack();
        foreach(char ch in s){
    
            if(Array.IndexOf(new char[]{
    '(','[','{'}, ch) >= 0){
    
                map.Push(ch);
            }else{
    
                if(map.Count == 0){
    
                    return false;
                }
                if(Math.Abs(ch - (char)map.Peek()) <= 2){
    
                    map.Pop();
                }else{
    
                    return false;
                }
            }
        }

        return map.Count == 0 ? true : false;
    }
}
原网站

版权声明
本文为[PowerDon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280602300450.html