[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;
        }
    }

 

posted on 2019-04-08 23:33  seako  阅读(124)  评论(0编辑  收藏  举报