MCPcopy Index your code
hub / github.com/Tiwarishashwat/InterviewCodes / canBeValid

Method canBeValid

checkIfParenthesisStringCanBeValid.java:2–32  ·  view source on GitHub ↗
(String s, String locked)

Source from the content-addressed store, hash-verified

1class Solution {
2 public boolean canBeValid(String s, String locked) {
3 int n = s.length();
4 if(n%2!=0) return false;
5 Stack<Integer> stack = new Stack<>();
6 Stack<Integer> unlocked = new Stack<>();
7 for(int i=0;i<n;i++){
8 char ch = s.charAt(i);
9 char state = locked.charAt(i);
10 if(state == '0'){
11 unlocked.push(i);
12 }else if(ch == '('){
13 stack.push(i);
14 }else{ // locked and closing
15 if(!stack.isEmpty()){
16 stack.pop();
17 }else{
18 if(!unlocked.isEmpty()){
19 unlocked.pop();
20 }else{
21 return false;
22 }
23 }
24 }
25 }
26
27 while(!stack.isEmpty() && !unlocked.isEmpty() && stack.peek() < unlocked.peek()){
28 stack.pop();
29 unlocked.pop();
30 }
31 return (stack.isEmpty());
32 }
33}

Callers

nothing calls this directly

Calls 3

pushMethod · 0.80
popMethod · 0.80
isEmptyMethod · 0.45

Tested by

no test coverage detected