[Leetcode] Valid Parentheses

Posted seako

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Valid Parentheses相关的知识,希望对你有一定的参考价值。

字串是不是由合法的括號組組成

 

public class Solution
    {
        /// <summary>
        /// \'(\' 40, \')\'41, \'{\'123, \'}\'125, \'[\'91 and \']\'93
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public bool IsValid(string s)
        {
            //空字串也合法
            if (string.IsNullOrEmpty(s))
                return true;
            //括號一定是兩兩成對 排除字元陣列奇數個
            if (s.Length % 2 > 0)
                return false;

            char[] arr = s.ToCharArray();
            //兩個直接判斷
            if (s.Length == 2)
            {
                return ((((int)arr[1] - (int)arr[0] == 2) || (int)arr[1] - (int)arr[0] == 1));
            }
            //使用stack 如果有剩下未pop的 就是非法
            Stack stack = new Stack();
            char poper = \'0\';
            char current = \'0\';
            bool result = true;
            for(int i =0; i < arr.Length; i++)
            {
                current = arr[i];
                if (current == \'(\' || current == \'[\' || current == \'{\')
                {
                    stack.Push(arr[i]);
                    continue;
                }
                else //(current == \')\' || current == \']\' || current == \'}\')
                {
                    //\')\'的數量多於\'(\' 直接false
                    if(stack.Count == 0)
                    {
                        result = false;
                        break;
                    }
                    poper = (char)stack.Pop();
                }

                //找到一個不是成對的馬上false
                if((((current - poper == 2) || current - poper == 1)) == false)
                {
                    result = false;
                    break;
                }
            }
            stack = null;
            if (result == true)
            {
                return stack.Count == 0;
            }

            return result;
        }
    }

 

以上是关于[Leetcode] Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 20.Valid Parentheses

LeetCode Valid Word Square

leetcode20. Valid Parentheses

LeetCode-Valid Palindrome

LeetCode 242. Valid Anagram

leetcode 242. Valid Anagram