Java 检查给定字符串是否具有相同匹配的括号
在网上发现了一些有趣的解决问题的问题,在这里Java 检查给定字符串是否具有相同匹配的括号,java,Java,在网上发现了一些有趣的解决问题的问题,在这里 You are to check the given String str if they contains matching parenthesis. 输入示例:[]、[(])、{[]}、{[}、{[}、{[}、{]} 示例输出:相等、相等、相等、不相等、不相等 我已经设法用基础知识完成了这个特性的需求,只是想知道是否有更好的方法来实现它 String str = "{[(])}(){}"; int pairs = 0; bool
You are to check the given String str if they contains matching parenthesis.
输入示例:[]、[(])、{[]}、{[}、{[}、{[}、{]}
示例输出:相等、相等、相等、不相等、不相等
我已经设法用基础知识完成了这个特性的需求,只是想知道是否有更好的方法来实现它
String str = "{[(])}(){}";
int pairs = 0;
boolean unableToFind = false;
ArrayList<Character> anChar = new ArrayList<Character>();
for (int i = 0; i < str.length(); i++) {
anChar.add(str.charAt(i));
}
if (str.length() % 2 == 0) {
while (pairs != str.length() / 2) {
for (int i = 1; i < anChar.size(); i++) {
char a = (char) anChar.get(0);
char b = (char) anChar.get(i);
if (a == '{' && b == '}' || a == '[' && b == ']' || a == '(' && b == ')') {
anChar.remove(i);
anChar.remove(0);
pairs++;
break;
} else {
if (i == anChar.size() - 1) { // reached end of array
unableToFind = true;
break;
}
}
}
if (unableToFind)
break;
}
if (pairs == str.length() / 2) {
System.out.println("Log#01: The String have balanced parenthesis");
} else {
System.out.println("Log#02: The String do not have balanced parenthesis. (" + pairs + "/" + str.length() / 2 + " pairs found)");
}
} else {
System.out.println("Log#03: The String do not have even numbers of parenthesis");
}
String str=“{[(])}(){}”;
整数对=0;
布尔值unableToFind=false;
ArrayList anChar=新的ArrayList();
对于(int i=0;i
您的方法过于复杂。您只需要三个计数器-countRound
、countSquare
和countCurly
。将所有三个字符初始化为零,然后逐个字符遍历字符串。如果你看到一个圆括号,增加它的计数器;如果是右括号,则减小其相应的计数器。循环结束后,所有三个计数器必须为零;否则,括号的数目不匹配
注意:这不会检查括号是否平衡,因为您的示例不需要它(即,
“[(])”
即使输入不平衡也会产生“相等”
。只需使用堆栈即可。您需要检查字符串中的每个字符,当找到右括号时,查看堆栈顶部是否有适当的右括号。逻辑如下所示:
char c = input.charAt(i);
if(c == ')' || c == '}' || c == ']') {
if(stack.isEmpty())
return false;
Character stackTop = stack.pop();
if( (c == ')' && stackTop != '(') ||
(c == '}' && stackTop != '{') ||
(c == ']' && stackTop != '[') )
return false;
} else
stack.push(c);
对于像“{}”这样的情况,堆栈将在末尾包含第一个“{”,因此请检查它是否为空
不确定您给出的示例。如果对于“[{(]})”,结果是“相等”,当字符串明显不平衡时,结果是:)不如前面的答案优雅,但它可以工作。
检查括号对的计数是否匹配
public class EqualClass {
public static void main(String[] args) {
String input = "[ ] , [ ( ] ) , { [ ] } , { [ } ] , { [ } ) , { ] }";
String[] tokens = input.split(",");
char[] bracketTypes = { '[', '{', '(' };
char[] oppositeBracketType = { ']', '}', ')' };
for (String token : tokens) {
boolean equal = true;
char[] characters = token.toCharArray();
for (int indx = 0; indx < bracketTypes.length; indx++) {
if (EqualClass.Test(characters, bracketTypes[indx]) != EqualClass
.Test(characters, oppositeBracketType[indx])) {
equal = false;
break;
}
}
if (!equal) {
System.out.println(token + " Not Equal");
} else {
System.out.println(token + " Equal");
}
}
}
public static int Test(char[] tokenOfCharacter, char bracketType) {
int count = 0;
for (char character : tokenOfCharacter) {
if (character == bracketType) {
count += 1;
}
}
return count;
}
}
公共类EqualClass{
公共静态void main(字符串[]args){
字符串输入=“[]、[(])、{[]}、{[}]、{[}、{[}、{]}”;
String[]tokens=input.split(“,”);
char[]bracketTypes={'[','{'','('});
char[]oppositeBracketType={']','}',')};
for(字符串标记:标记){
布尔等于真;
char[]characters=token.toCharArray();
对于(int indx=0;indx
这可能是一个更好的提问方式:我投票将这个问题作为主题外的问题来结束,因为它属于代码审查。通常,你会使用一个堆栈来完成类似的事情。只需迭代字符串。当你遇到一个打开的paren时,将一个令牌推到堆栈上,当你遇到一个关闭的paren时,它会弹出。这是CS 102;有很多在线示例。我不知道这是否是一项要求,但如果计数得到-1不相等,我会将其设置为在打开之前关闭。@Rubico我自己也不确定,因为OP的示例没有显示或解释这种情况。但是,由于平衡不是一项要求,我会怀疑计数就是它的全部。实现可能更好。但是数据结构的选择对+1@Kent是的,先生。我在写的时候就意识到了。懒惰占了上风。:p你能用完整的解决方案更新答案吗?@saikumarm我一直在考虑将负载转移到一个函数,该函数检查一对(堆栈顶部和当前字符)是否有效(使用类常量)。你认为这是个好主意吗?@Kent我刚刚就我想到的另一个备选方案添加了一条评论。如果这不是你正在考虑的实现,也许我们可以一起想出一些好主意?