Created
August 21, 2020 05:31
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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