Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace valis_parantheses_leetcode
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- //Console.WriteLine(IsValid(Console.ReadLine()).ToString());
- Console.WriteLine(IsValid("{}[]()(})").ToString());
- }
- public static bool IsValid(string s)
- {
- Console.WriteLine(s);
- if (s.Length % 2 != 0)
- {
- return false;
- }
- List<char> opened = new();
- foreach (char current in s)
- {
- if (IsOpeningBracket(current))
- {
- opened.Add(current);
- }
- else
- {
- // Check if there's an opened bracket to match with
- if (opened.Count > 0 && IsMatchingBracket(opened[opened.Count - 1], current))
- {
- // If it matches, pop the last opening bracket from the list
- opened.RemoveAt(opened.Count - 1);
- }
- else
- {
- // If it doesn't match or no opened bracket is available, return false
- return false; // Invalid bracket sequence
- }
- }
- }
- // If all opened brackets are matched, the list should be empty
- return opened.Count == 0; // Return true if valid, false if invalid
- }
- // Check if a character is an opening bracket
- private static bool IsOpeningBracket(char c)
- {
- return c == '(' || c == '{' || c == '[';
- }
- // Check if the opening and closing brackets match
- private static bool IsMatchingBracket(char opening, char closing)
- {
- return (opening == '(' && closing == ')') ||
- (opening == '{' && closing == '}') ||
- (opening == '[' && closing == ']');
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment