. Given a string of expression, a+b/c. Please use a stack to re-order the expression into abc/+.
时间: 2024-04-30 18:22:05 浏览: 105
a+b.c
可以使用栈来实现字符串的重新排列,具体步骤如下:
1. 遍历原始字符串,将每个字符依次入栈;
2. 当遇到斜杠“/”时,将栈中的元素全部出栈并组成新的字符串,再将斜杠“/”添加到新字符串的末尾;
3. 最后将新字符串返回即可。
代码示例:
```python
def reorder_expression(s):
stack = []
for c in s:
if c == '/':
tmp = ''
while stack:
tmp += stack.pop()
tmp += '/'
return tmp
stack.append(c)
return ''.join(stack)
# 测试
print(reorder_expression("a b/c")) # abc/
```
阅读全文