我怎么能用递归编程来做这个程序?
问题描述:
- 编写用于检查字符串中的括号的递归和非递归函数。
示例:
输入字符串:(a( b(c)d)e)
输出:true
- Write recursive and non-recursive functions that check parenthesis in a string.
Example:
Input string: (a(b(c)d)e)
Output: true
答
因为这有很多功课,我会给你不代码。
但是,它并不复杂。
非递归:
0)创建一个整数计数器,设置为零。
1)循环通过字符串中的每个字符(一个foreach
循环是完美的)
1.0)如果字符是''('',则增加按一个计算
1.1)如果字符是'')'',则将计数减少一个
2)循环后,检查计数 - 如果是零,所有括号匹配。
递归:
我不会为此使用递归。破解一个简单的坚果是一把大锤......
Since this smells lots of homework, I''ll give you no code.
But, it''s not complex.
Non recursive:
0) Create a integer counter , set to zero.
1) Loop through each character in the string (aforeach
loop is perfect for this)
1.0) If the character is a ''('', increment the count by one
1.1) If the character is a '')'', decrement the count by one
2) After the loop, check the count - if it is zero, all brackets match.
Recursive:
I wouldn''t use recursion for this. It''s a sledgehammer to crack a simple nut...