查找外部括号的计数 [英] Finding the count of external Parenthesis

查看:96
本文介绍了查找外部括号的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图找出找到外括号计数的解决方案。

您将在下面的示例中更清楚地了解外部括号的含义。假设给定的表达式始终有效。



I am trying to figure out the solution for finding the count of external parenthesis.
You will have more clarity on what i mean by external parenthesis in the below examples. Assume that the given expression will always be valid.

(a+b)                   //External parenthesis count =  1
(a+b)*(a-b)             //External parenthesis count =  0 
((a+b)*(a-b))           //External parenthesis count =  1
(((a+b)*(a-b)))         //External parenthesis count =  2
((a))                   //External parenthesis count =  2
(a + (b*c))             //External parenthesis count =  1
(a+b)+c                 //External parenthesis count =  0



我试过这个并且不知何故无法得到正确的逻辑。

所以我正在寻求创意。我从逻辑的角度来看更多。


I have tried this and somehow not able to get the right logic.
So i am reaching out for ideas. I am looking more from a logic perspective.

推荐答案

(a+b)                   //External parenthesis count =  1
(a+b)*(a-b)             //External parenthesis count =  0 
((a+b)*(a-b))           //External parenthesis count =  1
(((a+b)*(a-b)))         //External parenthesis count =  2
((a))                   //External parenthesis count =  2
(a + (b*c))             //External parenthesis count =  1
(a+b)+c                 //External parenthesis count =  0





对于每个()对删除(包括括号)不包含任何括号本身,例如(a + b)不包含(a + b * c )。





For each ( ) pair delete ones (including the parenthesis) that don't contain any parenthesis themselves, eg (a+b) doesn't but (a + (b*c)) does.

                   //External parenthesis count =  1
*             //External parenthesis count =  0 
(*)           //External parenthesis count =  1
((*))         //External parenthesis count =  2
()                   //External parenthesis count =  2
(a + )             //External parenthesis count =  1
+c                 //External parenthesis count =  0





现在只计算左边的括号对。请注意,这不适用于(a + b)或((a)),因此当括号仅存在于开头和结尾时,您可能需要一个特殊情况。



Now just count the parenthesis pairs left. Note this doesn't work for (a+b) or ((a)) so you might need a special case for when parenthesis only exists at the beginning and end.


externalCount = 0
loop
  if first or last chars are not parens
    exit loop
  Remove the external pair of parentheses.
  If the result is not well-formed
    exit loop
  externalCount++
  repeat loop
end loop



确定它是否格式正确:


To determine if it is well-formed:

counter = 0
scan across the expression:
  if '(' then counter++
  if ')' then counter--
well formed if at end of the scan the counter is 0 and never went negative.


这篇关于查找外部括号的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆