-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem2116.java
More file actions
96 lines (89 loc) · 2.48 KB
/
Problem2116.java
File metadata and controls
96 lines (89 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.util.Scanner;
public class Problem2116 {
// Check If a Parantheses String Can Be Valid
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
int t=obj.nextInt();
obj.nextLine();
while(t-->0){
String s=obj.nextLine();
String lock=obj.nextLine();
Solution sc=new Solution();
System.out.println(sc.canBeValid(s, lock));
Solution2116 sc1=new Solution2116();
System.out.println(sc1.canBeValid(s, lock));
}
obj.close();
}
}
class Solution2116{
public boolean canBeValid(String s,String lock){
int n=s.length();
if(n%2!=0) return false;
int open=0,close=0,card=0;
for(int i=0;i<n;i++){
if(lock.charAt(i)=='0'){
card++;
}else if(s.charAt(i)=='('){
open++;
}else{
close++;
}
if((card+open)<close){
return false;
}
}
open=0;close=0;card=0;
for(int i=n-1;i>=0;i--){
if(lock.charAt(i)=='0'){
card++;
}else if(s.charAt(i)=='('){
open++;
}else{
close++;
}
if((card+close)<open){
return false;
}
}
return true;
}
}
class Solution {
public boolean canBeValid(String s, String locked) {
int n = s.length();
if (n % 2 != 0) {
return false; // Odd length can't be balanced
}
int opening = 0, closing = 0;
int wildCard = 0;
for (int i = 0; i < n; ++i) {
if (locked.charAt(i) == '0') {
wildCard++;
} else if (s.charAt(i) == '(') {
opening++;
} else {
closing++;
}
// Overbalanced ')' check
if (wildCard < (closing - opening)) {
return false;
}
}
opening = closing = wildCard = 0;
for (int i = n - 1; i >= 0; --i) {
if (locked.charAt(i) == '0') {
wildCard++;
} else if (s.charAt(i) == '(') {
opening++;
} else {
closing++;
}
// Overbalanced '(' check
if (wildCard < (opening - closing)) {
return false;
}
}
return true;
}
}