Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
matching parenthesis
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { const char LeftParenthesis = '('; const char RightParenthesis = ')'; static bool isBalancedWithStack(string str) { if (str.Length <= 1 || str.Equals(null)) return false; var items = new Stack<int>(str.Length); int errorAt = -1; for (int i = 0; i < str.Length; i++) { if (str[i].Equals(LeftParenthesis)) items.Push(i); else if (str[i].Equals(RightParenthesis)) { if (items.Count == 0) { errorAt = i + 1; return false; } items.Pop(); } } if (items.Count > 0) { errorAt = items.Peek() + 1; return false; } return true; } static bool isBalancedWithoutStack(string str) { int count = 0; if (str.Length <= 1) return false; for (int i = 0; i < str.Length; i++) { if (str[i].Equals('(')) count++; else if (str[i].Equals(')')) { count--; if (count < 0) return false; } } return (count == 0); } static bool checkParentheses(string str) { if (str.Length <= 1) return false; int count = 0; for (int i = 0; i < str.Length; i++) { switch (str[i]) { case '(': count++; break; case ')': count--; if (count < 0) return false; break; } } return (count == 0); } public static void Main(string[] args) { string[] arrSample = new string[] { " ", "", "(", "()))))))", "(()((fff))())", "(()", "((((()))))", "(()(((())))())", "(()(((())))()", "()()()()()()()()()()()()" }; for (int i = 0; i < arrSample.Length; i++) { if (isBalancedWithStack(arrSample[i])) { Console.WriteLine("{0} is True", arrSample[i]); } else { Console.WriteLine("{0} is False", arrSample[i]); } if (isBalancedWithoutStack(arrSample[i])) { Console.WriteLine("{0} is True", arrSample[i]); } else { Console.WriteLine("{0} is False", arrSample[i]); } if (checkParentheses(arrSample[i])) { Console.WriteLine("{0} is True", arrSample[i]); } else { Console.WriteLine("{0} is False", arrSample[i]); } Console.WriteLine(); } } } } } }
run
|
edit
|
history
|
help
0
Collection_ basic datastructure brushup
MockTest
DateTime change clock
loop break continue
Logistics Predictor 5
Why do my posts keep getting deleted?
jjj2
case2
azs dasx
Trabbd