Skip to content

Instantly share code, notes, and snippets.

@AbhiAgarwal192
Created August 21, 2020 05:31
Show Gist options
  • Save AbhiAgarwal192/89e499445575f9e0500ccca4547489c5 to your computer and use it in GitHub Desktop.
Save AbhiAgarwal192/89e499445575f9e0500ccca4547489c5 to your computer and use it in GitHub Desktop.
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
public class Solution {
public bool IsValid(string s) {
int len = s.Length;
if(len == 0){
return true;
}
var stack = new Stack<char>();
for(int i=0;i<len;i++){
if(s[i]=='(' || s[i] == '{' || s[i] == '['){
stack.Push(s[i]);
}
else{
if(stack.Count==0){
return false;
}
var c = stack.Pop();
if(s[i] == ')' && c!='('){
return false;
}
if(s[i] == '}' && c!='{'){
return false;
}
if(s[i] == ']' && c!='['){
return false;
}
}
}
if(stack.Count!=0){
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment