All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0020_valid_parentheses.Solution.cs Maven / Gradle / Ivy

There is a newer version: 1.8
Show newest version
namespace LeetCodeNet.G0001_0100.S0020_valid_parentheses {

// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #String #Stack
// #Data_Structure_I_Day_9_Stack_Queue #Udemy_Strings #Big_O_Time_O(n)_Space_O(n)
// #2023_12_26_Time_53_ms_(96.68%)_Space_39.3_MB_(10.78%)

using System;
using System.Collections.Generic;

public class Solution {
    public bool IsValid(string s) {
        Stack stack = new Stack();
        for (int i = 0; i < s.Length; i++) {
            char c = s[i];
            if (c == '(' || c == '[' || c == '{') {
                stack.Push(c);
            } else if (c == ')' && stack.Count > 0 && stack.Peek() == '(') {
                stack.Pop();
            } else if (c == '}' && stack.Count > 0 && stack.Peek() == '{') {
                stack.Pop();
            } else if (c == ']' && stack.Count > 0 && stack.Peek() == '[') {
                stack.Pop();
            } else {
                return false;
            }
        }
        return stack.Count == 0;
    }
}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy