import java.util.Stack;
public class Parenthesis {
public static boolean isValid(String str){
Stack<Character> s=new Stack<>();
int i=0;
while(i<str.length()){
if(str.charAt(i)=='('||str.charAt(i)=='{'||str.charAt(i)=='[') s.push(str.charAt(i));
if(!s.isEmpty()){
if((str.charAt(i)==')'&&s.peek()=='(')
||(str.charAt(i)=='}'&&s.peek()=='{')
||(str.charAt(i)==']'&&s.peek()=='[')){
s.pop();
}
}
i++;
}
return s.isEmpty();
}
public static boolean duplicateParenthesis(String str){
if(isValid(str)){
Stack<Character> s=new Stack<>();
for(int i=0;i<str.length();i++){
if(str.charAt(i)==')'){
int count=0;
while(s.pop()!='(') count++;
if(count==0) return true;
}
else s.push(str.charAt(i));
}
}
return false;
}
public static void main(String[] args){
String str="((a+b)+((c+d)))";
System.out.println(duplicateParenthesis(str));
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter