20. Valid Parentheses
Input: s = "()"
Output: trueInput: s = "()[]{}"
Output: trueInput: s = "(]"
Output: falseInput: s = "([)]"
Output: falseInput: s = "{[]}"
Output: trueLast updated
Input: s = "()"
Output: trueInput: s = "()[]{}"
Output: trueInput: s = "(]"
Output: falseInput: s = "([)]"
Output: falseInput: s = "{[]}"
Output: trueLast updated
public class Solution {
public bool IsValid(string s) {
if(s == ""){
return true;
}
var s_array = s.ToCharArray();
if(s_array.Length % 2 != 0){
return false;
}
var stack = new Stack<char>();
foreach(char c in s_array){
if(c == '(' || c == '{' || c == '['){
stack.Push(c);
}
else{
if(c == ')' && (stack.Count == 0 || stack.Pop() != '(')){
return false;
}
else if(c == '}' && (stack.Count == 0 || stack.Pop() != '{')){
return false;
}
else if(c == ']' && (stack.Count == 0 || stack.Pop() != '[')){
return false;
}
}
}
return stack.Count == 0 ? true : false;
}
}