- Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
- An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
Input: s = "()[]{}"
Output: true
Example 3:Input: s = "(]"
Output: false
Constraints:- 1 <= s.length <= 104
- s consists of parentheses only '()[]{}'.
Java:
class Solution {
public boolean isValid(String s) {
HashMap<Character, Character> map = new HashMap<>();
map.put(")", "(");
map.put("]", "[");
map.put("}", "{");
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char curr = s.CharAt(i);
if (map.containsKey(curr)) {
char pop = stack.size() != 0 ? stack.pop() : '#';
if (pop != map.get(curr)){
return false;
}
} else {
stack.push(curr)
}
}
return stack.isEmpty();
}
}
Python:class Solution:
def isValid(self, s: str) -> bool:
while '()' in s or '[]'in s or '{}' in s:
s = s.replace('()','').replace('[]','').replace('{}','')
return False if len(s) !=0 else True
No comments:
Post a Comment