How to check that in the text everyone is '(' closed ')'?
- 2use the stack - tym32167
- 3+1 for the word "bow" - Igor
- Keywords for googling "c # balanced parentheses" - Andrew
|
2 answers
For one type of parentheses
public bool IsValid(string s) { var count = 0; foreach (var c in s) { if (c == '(') count++; if (c == ')') { if (count == 0) return false; count--; } } return count == 0; } For different types of brackets
public bool IsValid2(string s) { var stack = new Stack<char>(); foreach (var c in s) { switch (c) { case '{': case '(': case '[': stack.Push(c); break; case '}': if (stack.Count == 0) return false; if (stack.Pop() != '{') return false; break; case ']': if (stack.Count == 0) return false; if (stack.Pop() != '[') return false; break; case ')': if (stack.Count == 0) return false; if (stack.Pop() != '(') return false; break; } } return stack.Count == 0; } |
static void Main(string[] args) { var test = "text ( hello) no me(1)-(2)-(3)-(4-(5)-6)"; Console.WriteLine(All(test)); Console.ReadKey(); } static bool All(string h) { return h.Where(v => v == '(').Count() == h.Where(v => v == ')').Count(); } - 2
")))) как эта строка отработает с вашим решением? (((("- tym32167 2:53 pm - I do not know everything can be - Sasuke
|