Skip to content

Commit 56b77ec

Browse files
committed
Add solution #2116
1 parent ea5d5f3 commit 56b77ec

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,7 @@
383383
2095|[Delete the Middle Node of a Linked List](./2095-delete-the-middle-node-of-a-linked-list.js)|Medium|
384384
2099|[Find Subsequence of Length K With the Largest Sum](./2099-find-subsequence-of-length-k-with-the-largest-sum.js)|Medium|
385385
2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy|
386+
2116|[Check if a Parentheses String Can Be Valid](./2116-check-if-a-parentheses-string-can-be-valid.js)|Medium|
386387
2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy|
387388
2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy|
388389
2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 2116. Check if a Parentheses String Can Be Valid
3+
* https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/
4+
* Difficulty: Medium
5+
*
6+
* A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid
7+
* if any of the following conditions is true:
8+
* - It is ().
9+
* - It can be written as AB (A concatenated with B), where A and B are valid parentheses
10+
* strings.
11+
* - It can be written as (A), where A is a valid parentheses string.
12+
*
13+
* You are given a parentheses string s and a string locked, both of length n. locked is a
14+
* binary string consisting only of '0's and '1's. For each index i of locked,
15+
* - If locked[i] is '1', you cannot change s[i].
16+
* - But if locked[i] is '0', you can change s[i] to either '(' or ')'.
17+
*
18+
* Return true if you can make s a valid parentheses string. Otherwise, return false.
19+
*/
20+
21+
/**
22+
* @param {string} s
23+
* @param {string} locked
24+
* @return {boolean}
25+
*/
26+
var canBeValid = function(s, locked) {
27+
if (s.length % 2) return false;
28+
29+
let symmetrical = 0;
30+
for (let i = 0; i < s.length; i++) {
31+
if (locked[i] === '0' || s[i] === '(') {
32+
symmetrical++;
33+
} else {
34+
symmetrical--;
35+
}
36+
if (symmetrical < 0) {
37+
return false;
38+
}
39+
}
40+
41+
symmetrical = 0;
42+
for (let i = s.length - 1; i >= 0; i--) {
43+
if (locked[i] === '0' || s[i] === ')') {
44+
symmetrical++;
45+
} else {
46+
symmetrical--;
47+
}
48+
if (symmetrical < 0) {
49+
return false;
50+
}
51+
}
52+
53+
return true;
54+
};

0 commit comments

Comments
 (0)