首页 > 其他 > 详细

[Leetcode] Valid Parentheses

时间:2019-04-08 23:56:17      阅读:184      评论:0      收藏:0      [点我收藏+]

技术分享图片

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

 

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

原文:https://www.cnblogs.com/seako/p/10674361.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!