/** input str: string to search * num: the number of bracket to match, i.e, 1,2,3... * output the index of the matching right bracket in str * -1 if failed */ public static int getMatchingBra(String str, int num) { int index = 0; int count = num; while((index = str.indexOf( "(",index)+1) != 0 &&count != 0) count--; count = 1; for(int i = index;i < str.length();i++) { char ch = str.charAt(i); if(ch == '(') count++; else if(ch == ')') { count--; if(count == 0) return i; } } return -1; }
每次碰到“(”就push,碰到“)”就pop,pop出来的“(”就是与之对应的“)”
如果只是这么简单的问题的话,我们也可以用一个计数器来模拟Stack:每次碰到“(”就++,碰到“)”就--,
如果就着一个表达式的话就简单了
可比用楼上的方法
* num: the number of bracket to match, i.e, 1,2,3...
* output the index of the matching right bracket in str
* -1 if failed
*/
public static int getMatchingBra(String str, int num) {
int index = 0;
int count = num;
while((index = str.indexOf( "(",index)+1) != 0 &&count != 0)
count--;
count = 1;
for(int i = index;i < str.length();i++) {
char ch = str.charAt(i);
if(ch == '(')
count++;
else if(ch == ')') {
count--;
if(count == 0)
return i;
}
}
return -1;
}
Stack stack=new Stack();
System.out.println("开始:"+index);
for(int i=index;i<Str.length();i++){
char c=Str.charAt(i);
if(c=='('){
stack.push("wux");
}
if(c==')'){
stack.pop();
}
if(stack.empty()){
System.out.println("结束:"+i);
break;
}
} }