java 平衡括号,如何计算?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31849977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Balanced parenthesis, how to count them?
提问by Thierry L
I need to write a java program that tells you if the parenthesis are balanced in a string, I can't find the correct way to do it though.
I already know I am going to use a loop to count the open and closed parenthesis "(" = 1 and ")" = -1
stored in an integer that would come back as 0
or anything else.
我需要编写一个java程序来告诉你括号是否在字符串中平衡,但我找不到正确的方法来做到这一点。我已经知道我将使用一个循环来计算"(" = 1 and ")" = -1
存储在一个整数中的开括号和闭括号,该整数将作为0
或其他任何东西返回。
I just don't know how to count the parenthesis that way.
我只是不知道如何以这种方式计算括号。
Edit: To be clearer, all i really need is a way to count the parentheses and i am blocked because i can't work with something like :
编辑:更清楚地说,我真正需要的是一种计算括号的方法,但我被阻止了,因为我无法使用以下内容:
if (args[i] == '(') //the interpreter will not let me compare strings with chars count++;
if (args[i] == '(') //解释器不会让我将字符串与字符 count++ 进行比较;
Edit 2 :
编辑2:
public class Testing_grounds {
public static void main(String[] args) {
String str = args[];
char RetV[] = str.toCharArray();
int counter = 0;
for (int n = 0; n <= RetV.length; n++) {
if (RetV[n] == '(')
counter++;
else if (RetV[n] == ')')
counter--;
}
if (counter == 0)
System.out.println("The parentheses are balenced!");
else if(counter < 0)
System.out.println("There are to many closed parenthesis!");
else if(counter > 0)
System.out.println("There are to many opened parenthesis!");
}
}
This is pretty much the code i'm going for (i'm trying to get the toCharArray() method to work but i keep getting class expected error on the 3rd line. That line is there because it won't let me do : args.toCharArray)
这几乎是我要使用的代码(我试图让 toCharArray() 方法工作,但我一直在第 3 行收到类预期错误。该行在那里是因为它不会让我这样做: args.toCharArray)
Remember that i need to do this with an input and not a string already present in the code.
请记住,我需要使用输入而不是代码中已经存在的字符串来执行此操作。
回答by castarco
If you scan the string character by character, then you can do something like this:
如果逐个字符扫描字符串,则可以执行以下操作:
int counter = 0;
for (int i=0; i<text_length; i++) {
if (text[i] == '(') counter++;
else if (text[i] == ')') counter--;
if (counter < 0) break;
}
if (counter != 0) error();
This code takes into account the order of the parenthesis, so ")(" will be detected as an error.
此代码考虑了括号的顺序,因此“)(”将被检测为错误。
EDIT:
编辑:
To do the same in Java you can do:
要在 Java 中执行相同操作,您可以执行以下操作:
int counter = 0;
for (char ch : text.toCharArray())
if (ch == '(') counter++;
else if (ch == ')') counter--;
if (counter < 0) break;
}
if (counter != 0) error();
Hope it helps.
希望能帮助到你。
回答by Mateusz Dymczyk
Actually you can do it in several ways:
实际上,您可以通过多种方式做到这一点:
1) use a stack. Push a value every time you see a (
and pop a value every time you see a )
. If there's nothing to pop (stack exception) then it's not balanced. This approach is nice because if you use a stack of char
you can easily extend it to handle other types of parenthesis by having a simple mapping of closing parenthesis to opening parenthesis (i.e. ] -> [, ) -> (, } -> {
) and checking if what you popped is ok for what you encountered in the string.
1)使用堆栈。每次看到 a 时推送一个值,每次看到 a 时(
弹出一个值)
。如果没有什么可弹出(堆栈异常),则它不平衡。这种方法很好,因为如果您使用一个堆栈,char
您可以轻松地扩展它以处理其他类型的括号,方法是通过将右括号到左括号(即] -> [, ) -> (, } -> {
)的简单映射并检查您弹出的内容是否适合您在细绳。
Something like this:
像这样的东西:
Stack<Character> openParens = new Stack<>();
for(Character ch: text.toCharArray()) {
if(ch == '(') {
openParens.push(ch);
} else if(ch == ')') {
if(openParens.empty()) {
return false; //unbalanced
} else {
openParens.pop();
}
}
}
return true;
This will not work if parenthesis order is not important, though.
但是,如果括号顺序不重要,这将不起作用。
2) use a counter, add 1
when you notice a (
and remove 1
when you see a )
. If you go below 0 return false (unbalanced). Or go until the end of the string and then check if the count is 0
, this will handle cases when you don't require ordering (just when the count of (
== )
)
2) 使用计数器,看到 a 时添加1
,看到 a 时(
删除。如果低于 0,则返回 false(不平衡)。或者直到字符串的末尾,然后检查计数是否为,这将处理您不需要排序的情况(仅当==计数时)1
)
0
(
)
@EDIT:
@编辑:
Ok so the problem is String str = args[];
won't compile if you don't provide the index (i.e. String str = args[0];
). Also you cannot call toCharArray()
on args
because that's a method defined on the String
class and args
is an arrayof String
s.
好的,String str = args[];
如果您不提供索引(即String str = args[0];
),则问题将无法编译。您也可以不叫toCharArray()
上args
,因为这是在定义的方法String
类args
是一个数组的String
秒。
I would not recommend passing the text you want to count that way, it's not easy to use afterwards. How about instead you ass a test file name containing your text and read that instead?
我不建议以这种方式传递您想要计算的文本,之后不容易使用。相反,您将一个包含您的文本的测试文件名改为阅读,如何?
回答by ThreeSidedCoin
Read the string from start to finish, use a stack to count the parentheses. Push only the opening parentheses into the stack, pop one if you encounter a closing parenthesis.
从头到尾读取字符串,使用堆栈计算括号。仅将左括号推入堆栈,如果遇到右括号则弹出一个。
So something like ((a+x)*(b+y)) would leave an empty stack at the end, which tells you the parentheses are balanced.
所以像 ((a+x)*(b+y)) 这样的东西会在最后留下一个空堆栈,这告诉你括号是平衡的。
Do you also need to consider the order eg:(a+b)))((?
您是否还需要考虑顺序,例如:(a+b)))((?
回答by Conner
well, if you want to count the number of balanced parenthesis in a string, following java code might help
好吧,如果你想计算一个字符串中平衡括号的数量,下面的java代码可能会有所帮助
int open=0,close=0;
Stack<Character> openbrace = new Stack<Character>();
for( char c : sample.toCharArray())
{
if(c=='(') {
openbrace.push(c);
open++;
}
else if(c==')') {
if(openbrace.isEmpty()==false) { openbrace.pop();}
close++;
}
}
if(open-close!=0)
System.out.println("unbalanced ");
else
System.out.println("balanced");
System.out.println(" count of balanced brace="+Math.min(open, close));
回答by Naeem
Function calculates the unbalanced brackets.
函数计算不平衡括号。
public static int bracketMatch(String bracketString) {
Stack<Character>opening = new Stack<Character>();
Stack<Character>closing = new Stack<Character>();
char [] brackets = bracketString.toCharArray();
for (char bracket: brackets) {
if (bracket == '(') {
opening.push(bracket);
} else if (bracket == ')') {
if (opening.size() > 0) {
opening.pop();
}
else {
closing.push(bracket);
}
}
}
return opening.size()+closing.size();
}
回答by Jaydeep Shil
Here is the working code which returns the matching count and -1 when unmatched.
这是返回匹配计数和不匹配时 -1 的工作代码。
public int matchedCount(){
Scanner scan = new Scanner(System.in);
Stack<Integer> stk = new Stack<Integer>();
System.out.println("Enter expression");
String exp = scan.next();
int len = exp.length();
System.out.println("\nMatches and Mismatches:\n");
int counter = 0;
for (int i = 0; i < len; i++)
{
char ch = exp.charAt(i);
if (ch == '(')
stk.push(i);
else if (ch == ')')
{
try
{
int p = stk.pop() + 1;
counter++;
}
catch(Exception e)
{
return -1;
}
}
}
while (!stk.isEmpty() )
return -1;
return counter;
}
回答by Nitesh Virani
You can take the difference using below code:
您可以使用以下代码来区分:
int diff = str.replaceAll("\(", "").length() - str.replaceAll("\)","").length();
if it is 0
then parenthesis are balanced.
如果是,0
则括号是平衡的。