class Solution:
def isValid(self, s):
if s == "":
return True
if len(s) < 2:
return False
pair_brkts = {
"{" : "}",
"(" : ")",
"[" : "]"
}
stack = []
for i in s:
if i in pair_brkts:
stack.append(i) #stack i(forward facing brackets) that also exists as keys in our pair_brkts dictionary)
#print("forward facing brackets", stack) #to see the contents of your stacked list
else:
if len(stack) == 0 or pair_brkts[stack.pop()] != i: #if stack list is empty or the value pair of last
#list item isnt same, return False, otherwise break out of loop
#print("backward facing brackets", stack) #print to see whats left of your list after
#looping is over for all your i(i.e brackets)
return False
if len(stack) > 0: #if stack list is not empty at this point, return False, else return True
return False
return True
Task = Solution()
print("1. ", Task.isValid("({[()]})"))
print("2. ", Task.isValid("()[]{}"))
print("3. ", Task.isValid("(]"))
class Solution:
def isValid (self, sequence: str):
'''
Function to pair if sequence contains valid parenthesis
:param sequence: Sequence of brackets
:return: True is sequence is valid else False
'''
stack = []
opening = set('([{')
closing = set(')]}')
pair = {')' : '(' , ']' : '[' , '}' : '{'}
for i in sequence :
if i in opening :
stack.append(i)
if i in closing :
if not stack :
return False
elif stack.pop() != pair[i] :
return False
else :
continue
if not stack :
return True
else :
return False
if __name__ == '__main__':
sequence = '{[()]}'
print(f'Is {sequence} valid ? : {Solution().isValid(sequence)}')
sequence1 = '{[()]}{]{}}'
print(f'Is {sequence1} valid ? : {Solution().isValid (sequence1)}')
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
class Solution {
public:
bool isValid(string s) {
}
};
class Solution {
public boolean isValid(String s) {
}
}
bool isValid(char * s){
}
public class Solution {
public bool IsValid(string s) {
}
}
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
};
# @param {String} s
# @return {Boolean}
def is_valid(s)
end
class Solution {
func isValid(_ s: String) -> Bool {
}
}
class Solution {
/**
* @param String $s
* @return Boolean
*/
function isValid($s) {
}
}
function isValid(s: string): boolean {
};