Filip13

valid_parentheses_leetcode

Oct 2nd, 2024
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | Source Code | 0 0
  1. namespace valis_parantheses_leetcode
  2. {
  3.     internal class Program
  4.     {
  5.         static void Main(string[] args)
  6.         {
  7.             //Console.WriteLine(IsValid(Console.ReadLine()).ToString());
  8.             Console.WriteLine(IsValid("{}[]()(})").ToString());
  9.         }
  10.         public static bool IsValid(string s)
  11.         {
  12.             Console.WriteLine(s);
  13.  
  14.             if (s.Length % 2 != 0)
  15.             {
  16.                 return false;
  17.             }
  18.  
  19.             List<char> opened = new();
  20.  
  21.             foreach (char current in s)
  22.             {
  23.                 if (IsOpeningBracket(current))
  24.                 {
  25.                     opened.Add(current);
  26.                 }
  27.                 else
  28.                 {
  29.                     // Check if there's an opened bracket to match with
  30.                     if (opened.Count > 0 && IsMatchingBracket(opened[opened.Count - 1], current))
  31.                     {
  32.                         // If it matches, pop the last opening bracket from the list
  33.                         opened.RemoveAt(opened.Count - 1);
  34.                     }
  35.                     else
  36.                     {
  37.                         // If it doesn't match or no opened bracket is available, return false
  38.                         return false; // Invalid bracket sequence
  39.                     }
  40.                 }
  41.             }
  42.  
  43.             // If all opened brackets are matched, the list should be empty
  44.             return opened.Count == 0; // Return true if valid, false if invalid
  45.         }
  46.  
  47.         // Check if a character is an opening bracket
  48.         private static bool IsOpeningBracket(char c)
  49.         {
  50.             return c == '(' || c == '{' || c == '[';
  51.         }
  52.  
  53.         // Check if the opening and closing brackets match
  54.         private static bool IsMatchingBracket(char opening, char closing)
  55.         {
  56.             return (opening == '(' && closing == ')') ||
  57.                    (opening == '{' && closing == '}') ||
  58.                    (opening == '[' && closing == ']');
  59.         }
  60.  
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment