从中缀转换为前缀时,为什么我们必须反转字符串 [英] Why do we have to reverse the string when converting from infix to prefix

查看:114
本文介绍了从中缀转换为前缀时,为什么我们必须反转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将中缀转换为前缀的第一步中,有人可以简单地解释为什么我们应该反转字符串吗?有其他替代方法可以转换吗?

In the first step itself of converting an infix to prefix can someone explain in simple terms why should we reverse the string? Is there any alternative method to convert?

推荐答案

是的,您绝对正确,如果必须将中缀转换为前缀,则必须从右向左扫描字符串.

Yes, you are absolutely right that if you have to convert infix to prefix then you have to scan the string from right to left.

为什么不从左到右?

如果您从左向右扫描,则将需要对字符串中的运算符有进一步的了解.

If you scan from left to right then you will require future knowledge of operators in the string.

示例1:

Infix  : 2+3
Prefix : +23

现在,当您将其从左向右转换时,您应该已经知道字符串中尚未出现的+.在这个特定示例中,这看起来很简单,现在考虑下面给出的另一个示例.

Now, when you convert it from left to right then you should have the knowledge of + that is yet to appear in the string. This looks simple in this particular example, now consider another example given below.

示例2:

Infix  : 2+3*4/5-6*7
Prefix : -+2/*345*67

现在,如果您从左向右扫描,那么当您扫描字符串的第0个索引时,程序应该了解-它将出现在字符串的第7个索引中,这可能是一项繁重的工作.

Now, if you scan from left to right then when you scan 0th index of string then the program should have knowledge of - which is going to appear in 7th index of string which could be a hectic job.

所以最安全的方法是从右到左扫描字符串.

So the safest way to do is to scan the string from right to left.

这篇关于从中缀转换为前缀时,为什么我们必须反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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