Difficulty: Easy
Topics: Strings, Stack, Algorithms
Companies: Relevant for interviews at top tech companies.
You are given a string s
containing only the characters '(', ')', '{', '}', '[', and ']'. Your task is to determine whether the input string is valid.
A string is considered valid if:
A single string s
consisting of the characters '(', ')', '{', '}', '[', and ']'.
1 <= s.length <= 10⁴
Return true
if the input string is valid.
Return false
otherwise.
Input:
s = "()"
Output:
true
Input:
s = "()[]{}"
Output:
true
Input:
s = "(]"
Output:
false
Input:
s = "([])"
Output:
true
https://leetcode.com/problems/valid-parentheses/description/
Loading component...
Loading component...
Main Function is not defined.
input: "{}()[]"
Output: True
public static void isValid(string s){
stack <char>sk;
for(int i = 0; i< s.length();i++)
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
sk.push(s[i]);
}
else{
if(s[i] == ')' || s[i] == ')' || s[i] == ')'){
if(sk.size() == 0){
return false;
}
else{
if(sk.top() != '(' && s[i] == ')' )){
return false;
}
else{
if(sk.top() != '{' && s[i] == '}' ){
return false;
}
else{
if(sk.top() != '[' && s[i] == ']' ){
return false;
}
else{
sk.pop();
}
}
}
}
}
}
for loop end
if(sk.size() == 0){
return true;
}
else{
return false;
}
}//function end
Utility Function is not required.