Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace Simple
- {
- class Program
- {
- #region valid
- static string validString = "" +
- "int a = 0;" +
- "int b = 10;" +
- "while(a+b<100){" +
- "a++;" +
- "str s = \"asd\"" +
- "};";
- #endregion
- #region not valid
- static string notValidString = "" +
- "int a = {0;" +
- "(int b = 10;" +
- "while}(a+b<100){" +
- "a++;)" +
- "};";
- #endregion
- static void Main(string[] args)
- {
- List<string> strings = new List<string>() { validString, notValidString, "{[(])}" };
- foreach (var str in strings)
- {
- Console.WriteLine($"string is { CheckValid(str)}");
- }
- }
- public static readonly char[] symbs = { '{', '[','(','\'','"','}',']',')'};
- private static bool CheckValid(string str){
- if (str == null)
- throw new ArgumentException("String is null");
- char[] lex = str.Where(c=> symbs.Contains(c)).ToArray();
- Stack<char> opens = new Stack<char>();
- foreach(var c in lex){
- switch(c){
- case '{':
- case '[':
- case '(':
- opens.Push(c);
- continue;
- case '"':
- case '\'':
- if (opens.Peek() != c){
- opens.Push(c);
- continue;}
- break;}
- //Закрывающие
- switch(c){
- case '}':
- if (opens.Peek() == '{')
- opens.Pop();
- break;
- case ']':
- if (opens.Peek() == '[')
- opens.Pop();
- break;
- case ')':
- if (opens.Peek() == '(')
- opens.Pop();
- break;
- case '\'':
- if (opens.Peek() == '\'')
- opens.Pop();
- break;
- case '"':
- if (opens.Peek() == '"')
- opens.Pop();
- break;}}
- return !opens.Any();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement