我想创建一个函数来检查字符串是否关闭了对括号以及它们是否有序。例如:
字符串“[] [] []”应返回true
字符串“{[(a b c)]}”应该返回true,
字符串“{[[}]}”应返回false,因为
我要检查的括号是否有“{”,“}”,“(”,“)”,“[”,“]”,“<”,“>”
这是我到目前为止的代码。 haveTheSameCount(String)检查每个开括号是否存在补码。 fillBracketsPosition(List,String,String)填充一个列表,其中包含每个括号在代码中出现的位置。我想我应该检查字符串中括号的每个位置,但我不知道我还能做什么。
package Algorithms;
import java.util.*;
import java.lang.*;
public class GetBracketPair {
public static final String brackets_allowed[] = {"{","}","[","]","<",">","(",")"};
public static void main(String args[]) throws InterruptedException {
boolean r1 = haveEnclosedBrackets("abcde");
boolean r2 = haveEnclosedBrackets("[]._.<>()");
boolean r3 = haveEnclosedBrackets("{((})){}");
//boolean r4 = haveEnclosedBrackets("{");
System.out.println(r1);
System.out.println(r2);
System.out.println(r3);
//System.out.println(r4);
}
// Given a certain string, the function have to ensure that contains a close bracket for every open bracket and should be in order
// First, we will check if the counter for each element is equal in the String
// Second, we will check if the order of each element is correct
public static boolean haveEnclosedBrackets(String str) throws InterruptedException {
boolean result = false;
result = haveTheSameCount(str);
return result;
}
public static boolean haveTheSameCount(String str) throws InterruptedException {
int count_brackets[] = {0,0,0,0,0,0,0,0};
List <Integer> list1 = new ArrayList<>();
boolean result = false;
for (int i = 0; i < brackets_allowed.length; i++) {
count_brackets[i] = str.length() - str.replace(brackets_allowed[i], "").length();
}
if ((count_brackets[0] == count_brackets[1]) && (count_brackets[2] == count_brackets[3]) && (count_brackets[4] == count_brackets[5]) && (count_brackets[6] == count_brackets[7])) {
result = true;
list1 = fillBracketsPosition(list1,str,"{");
if (list1 != null) {
for (Integer i : list1) {
System.out.println("Position of {: " + i);
}
}
}
return result;
}
public static List <Integer> fillBracketsPosition(List <Integer> positions, String str, String bracket) throws InterruptedException {
int pos = -1;
pos = str.indexOf(bracket);
//System.out.println("First Pos: " + pos);
if (pos != -1) {
positions.add(pos);
while (pos != -1) {
pos = str.indexOf(bracket,pos+1);
//System.out.println("Adding pos: " + pos);
Thread.sleep(500);
if (pos == -1) {
return positions;
}
positions.add(pos);
}
}
else {
//System.out.println("bracket doesn't exist");
positions = null;
}
return positions;
}
}