Valid Parenthesis String


Given a string s
containing only three types of characters: '('
, ')'
and '*'
, return true
if s
is valid.
The following rules define a valid string:
Any left parenthesis
'('
must have a corresponding right parenthesis')'
.Any right parenthesis
')'
must have a corresponding left parenthesis'('
.Left parenthesis
'('
must go before the corresponding right parenthesis')'
.'*'
could be treated as a single right parenthesis')'
or a single left parenthesis'('
or an empty string""
.
LeetCode Problem - 678
class Solution {
public boolean checkValidString(String s) {
// Variables to track open and closed brackets
int openBracket = 0;
int closedBracket = 0;
// Length of the string
int length = s.length()-1;
// Loop through the string
for(int i=0; i<=length; i++){
// If character is '(' or '*', increment openBracket count
if(s.charAt(i) == '(' || s.charAt(i) == '*'){
openBracket++;
} else
// If character is ')' decrement openBracket count
openBracket--;
// If character at the end of the string is ')' or '*', increment closedBracket count
if(s.charAt(length - i) == ')' || s.charAt(length - i) == '*'){
closedBracket++;
} else
// If character at the end of the string is '(' decrement closedBracket count
closedBracket--;
// If either openBracket or closedBracket count is negative, return false
if(openBracket < 0 || closedBracket < 0){
return false;
}
}
// If loop completes, return true
return true;
}//method
} // main
Subscribe to my newsletter
Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Gulshan Kumar
Gulshan Kumar
As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.