Browser tab content: Problem List Register or Sign in Premium Debugging... Run Submit…
- User
Browser tab content: Problem List Register or Sign in Premium Debugging... Run Submit Description Editorial Editorial Solutions Solutions Submissions Submissions Code Testcase Test Result Test Result 921. Minimum Add to Make Parentheses Valid Medium Topics Companies
A parentheses string is valid if and only if:
It is the empty string, It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.
You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.
For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))".
Return the minimum number of moves required to make s valid.
Example 1:
Input: s = "())" Output: 1
Example 2:
Input: s = "(((" Output: 3
Constraints:
1 <= s.length <= 1000 s[i] is either '(' or ')'. Accepted 545.2K Submissions 730.5K Acceptance Rate 74.6% Topics String Stack Greedy Companies Similar Questions Minimum Number of Swaps to Make the String Balanced Medium Discussion (199) Choose a type Preview Comment 💡 Discussion Rules
-
Please don't post any solutions in this discussion.
-
The problem discussion is for asking questions about the problem or for sharing tips - anything except for solutions.
-
If you'd like to share your solution for feedback and ideas, please head to the solutions tab and post it there.
Sort by:Best No comments yet. 1 2 3 4 20 Copyright ©️ 2024 LeetCode All rights reserved 4.6K 199 10 Online Java Auto 1 2 3 4 5 class Solution { public int minAddToMakeValid(String s) { } } Saved Ln 3, Col 9 You need to Login / Sign up to run or submit Case 1 Case 2 s = "())" 1 2 "())" "(((" Source
Tag
Remove distracting text, extract the programming question, provide simple, common, and optimized Java solution for it.
-
- Assistant
Problem Statement
You are given a parentheses string
s. In one move, you can insert a parenthesis at any position of the string. Your task is to return the minimum number of moves required to makesvalid. A parentheses string is valid if and only if it can be:- An empty string,
- Written as
AB(A concatenated with B), where A and B are valid strings, - Written as
(A), where A is a valid string.
Java Solution
To solve this problem, we can use a stack or simply keep track of the number of unmatched parentheses as we iterate through the string. Here is an optimized Java solution using a simple count: