[C#] Validparentheses 解法

判断如下方结果
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

使用 Stack 解法

static void Main(string[] args){    string a = "()[]";    Console.WriteLine(ValidParentheses2(a));}private static bool ValidParentheses2(string a){    Stack<char> sta = new Stack<char>();    foreach (var c in a)    {        if (c == '(') sta.Push(c);        else if (c == '[') sta.Push(c);        else if (c == '{') sta.Push(c);        else if (c == ')')        {            var top = sta.Pop();            if (top != '(')            {                return false;            }        }        else if (c == '}')        {            var top = sta.Pop();            if (top != '{')            {                return false;            }        }        else if (c == ']')        {            var top = sta.Pop();            if (top != '[')            {                return false;            }        }    }    return true;}

暴力解法

static void Main(string[] args){    string a = "()[]";    Console.WriteLine(ValidParentheses(a));}private static bool ValidParentheses(string a){    var temp = a;    Dictionary<string, string> dic = new Dictionary<string, string>            {                { "(", ")" },                { "[", "]" },                { "{", "}" }            };    for (int i = 0; i < a.Length; i += 2)    {        string first = temp.Substring(i, 1);        string end = temp.Substring(i + 1, 1);        if (!dic.ContainsKey(first)) return false;        if (dic[first] != end) return false;    }    return true;}  

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章