Pattern Length
Below code will find the maximum length of valid pattern i.e. pattern in which all the open brackets are closed
import java.util.Stack;
/**
* Below code will find the maximum length of valid pattern i.e. pattern in which all the open brackets are closed
* @author Nitin Agrawal
*
*/
public class MaxSeries {
public static void main(String[] args) {
// String str = "(([]))(())"; // 10
// String str = "]{[]}[]"; // 6
// String str = "]{{{{}}}}[]"; // 10
String str = "{[[)[{((()))}][[[[[[[[]]]]]]]]"; // 26
Stack<Character> stk = new Stack<>();
int max = 0;
int len = 0;
for(char ch : str.toCharArray()) {
if(ch == '(' || ch == '{' || ch == '[') {
if(max < len) {
max = len;
len = 0;
}
stk.push(ch);
}
else if (ch == ')' || ch == '}' || ch == ']') {
if(!stk.isEmpty()) {
char ch1 = stk.pop();
if(ch == ')' && ch1 == '(')
len = len + 2;
else if(ch == ']' && ch1 == '[')
len = len + 2;
else if(ch == '}' && ch1 == '{')
len = len + 2;
else {
if(max > len) {
max = len;
}
len = 0;
stk.clear();
}
}
}
}
if(stk.isEmpty())
System.out.println(max+len);
else
System.out.println(max > len ? max : len);
}
}
/**
* Below code will find the maximum length of valid pattern i.e. pattern in which all the open brackets are closed
* @author Nitin Agrawal
*
*/
public class MaxSeries {
public static void main(String[] args) {
// String str = "(([]))(())"; // 10
// String str = "]{[]}[]"; // 6
// String str = "]{{{{}}}}[]"; // 10
String str = "{[[)[{((()))}][[[[[[[[]]]]]]]]"; // 26
Stack<Character> stk = new Stack<>();
int max = 0;
int len = 0;
for(char ch : str.toCharArray()) {
if(ch == '(' || ch == '{' || ch == '[') {
if(max < len) {
max = len;
len = 0;
}
stk.push(ch);
}
else if (ch == ')' || ch == '}' || ch == ']') {
if(!stk.isEmpty()) {
char ch1 = stk.pop();
if(ch == ')' && ch1 == '(')
len = len + 2;
else if(ch == ']' && ch1 == '[')
len = len + 2;
else if(ch == '}' && ch1 == '{')
len = len + 2;
else {
if(max > len) {
max = len;
}
len = 0;
stk.clear();
}
}
}
}
if(stk.isEmpty())
System.out.println(max+len);
else
System.out.println(max > len ? max : len);
}
}