LeetCode 678: Valid Parenthesis String Solution
Master LeetCode problem 678 (Valid Parenthesis String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
678. Valid Parenthesis String
Problem Explanation
Explanation
To solve this problem, we can use a greedy approach where we maintain a lower and upper bound of the number of open left parentheses '(' that must be paired. We iterate through the string from left to right, updating these bounds based on the presence of '*' characters. If the upper bound becomes negative at any point, it means there are more ')' characters than '(' characters, and the string is invalid. At the end, we check if the lower bound is 0, indicating all '(' characters have been paired.
Time Complexity: O(n)
Space Complexity: O(1)
Solution Code
class Solution {
public boolean checkValidString(String s) {
int lower = 0, upper = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
lower++;
upper++;
} else if (c == ')') {
lower = Math.max(0, lower - 1);
upper--;
} else {
lower = Math.max(0, lower - 1);
upper++;
}
if (upper < 0) {
return false;
}
}
return lower == 0;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 678 (Valid Parenthesis String)?
This page provides optimized solutions for LeetCode problem 678 (Valid Parenthesis String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 678 (Valid Parenthesis String)?
The time complexity for LeetCode 678 (Valid Parenthesis String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 678 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 678 in Java, C++, or Python.