当给出起始括号的索引和给出java程序的String时,如何找到右括号的索引

时间:2014-04-25 10:50:24

标签: java string parsing

当字符串是(A + b +(c + d)+(a))

这里指数i:0 相应的右括号:14

2 个答案:

答案 0 :(得分:4)

使用stack存储括号并遍历字符串...堆栈是lifo,因此应该使得右括号变得容易。 Soemthing谎言:

char[] myArray = exampleString.toCharArray()
for(int i = startIndex;i<myArray.length;i++){
    if(myArray[i] == "("){
      myStack.push(myArray[i]);
    }
    if(myArray[i] == ")"){
      myStack.pop();
    }
    if(myStack.empty()){
      return i;// the closing index of parenthesis
    }
}

答案 1 :(得分:1)

1. Start from your index. increment your count of "(" to 1. 
2. Now, for each "(" you encounter, increment count by 1.
3. For each ")" decrement count by 1.
4. If count ==0, that's your closing brace.