题目:给定字符串,如"(A(B)(C(D)(E))F)",写一程序,求第n对括号里的内容。
突破口:确定括号index之后,只要找到此index的左括号的索引,然后向后遍历,左括号总数等于右括号总数时的索引即为结束点
- public static String getContent(int index,String src)
- {
- char[] cs=src.toCharArray();
- int count=1,countLeft=1,countRight=1;
- String result="";
- for(int i=0;i<cs.length;i++)
- {
- char c=cs[i];
- if(c=='(')
- {
- if(count==index)
- {
- for(int j=i;j<cs.length;j++)
- {
- char c2=cs[j];
- if(c2=='(')
- {
- countLeft++;
- }
- if(c2==')')
- {
- countRight++;
- }
- if(countLeft==countRight)
- {
- result=src.substring(i, j+1);
- break;
- }
- }
- break;
- }
- count++;
- }
- }
- return result;
- }
突破口:确定括号index之后,只要找到此index的左括号的索引,然后向后遍历,左括号总数等于右括号总数时的索引即为结束点