将字符串(如 (0&(1|0)|1) 和 (0|1) 转换为其对应的真值

Transform a string such as (0&(1|0)|1) & (0|1) into it's corresponding truth value

本文关键字:字符串 转换      更新时间:2023-10-16

我在一个采访论坛上发现了这个问题,觉得这是一个有趣的问题。用C++有什么简单的方法可以完成这项任务吗?例如,假设我们有函数声明:

bool _transform(string x); 
/* x is a combination of (, ), 0, 1, &, and | such that all expressions 
   start with a open and ending brace, and the function evaluates the 
   strings actual truth value 
*/

有什么有效且相对简单的方法可以做到这一点吗?我曾想过递归地用括号括起来,但这个问题似乎很难解决。

这只是表达式解析和求值的一个相当简单的练习,使用逻辑运算符而不是算术运算符。真的很琐碎。查找"递归下降表达式解析"或Dijkstra调车场算法。警告:有许多国产和其他类似的产品,其中大多数都有细微的缺陷或非线性性能。使用来源。

注意,标题中表达式的值为1.

这个问题的简单解决方案是基于堆栈的解析器。[递归下降是过分的。]

For each character in the string
  If it's a value (0 1)
    If top of stack is an operator
      Pop operator and value, evaluate
    Push value on the stack
  If it's an operator (&|) push it on the stack
  If it's a left parenthesis push it on the stack
  If it's a right parenthesis pop the value and the LP, push the value
At end, pop the value off the stack.

需要更多的代码来优雅地处理错误,但你已经明白了。它也忽略了优先级。

这个概念很容易扩展到任何类型的算术表达式,但您需要处理优先级才能得到正确的答案。这有效地将表达式从中缀转换为后缀表示法,并动态求值。