获取第n对括号里的内容

题目:给定字符串,如"(A(B)(C(D)(E))F)",写一程序,求第n对括号里的内容。 
Java代码 
  1. public static String getContent(int index,String src)  
  2.     {  
  3.         char[] cs=src.toCharArray();  
  4.         int count=1,countLeft=1,countRight=1;  
  5.         String result="";  
  6.         for(int i=0;i<cs.length;i++)  
  7.         {  
  8.             char c=cs[i];  
  9.             if(c=='(')  
  10.             {  
  11.                 if(count==index)  
  12.                 {  
  13.                     for(int j=i;j<cs.length;j++)  
  14.                     {  
  15.                         char c2=cs[j];  
  16.                         if(c2=='(')  
  17.                         {  
  18.                             countLeft++;  
  19.                         }  
  20.                         if(c2==')')  
  21.                         {  
  22.                             countRight++;  
  23.                         }  
  24.                         if(countLeft==countRight)  
  25.                         {  
  26.                             result=src.substring(i, j+1);  
  27.                             break;  
  28.                         }  
  29.                     }  
  30.                     break;  
  31.                 }  
  32.                 count++;  
  33.             }  
  34.         }  
  35.         return result;  
  36.     }  

突破口:确定括号index之后,只要找到此index的左括号的索引,然后向后遍历,左括号总数等于右括号总数时的索引即为结束点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值