博客
关于我
Leetcode: Ternary Expression Parser
阅读量:806 次
发布时间:2023-01-31

本文共 1415 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要计算一个包含嵌套三元表达式的字符串的结果。三元表达式由数字0-9,问号、冒号、T和F组成,其中T表示True,F表示False。表达式是从右到左结合的。我们可以使用栈来模拟这个过程,确保正确处理嵌套结构。

方法思路

我们将字符串从右到左遍历,每遇到一个问号时,弹出栈顶的两个元素,这两个元素分别是左边的表达式和右边的表达式。根据当前字符是T还是F,决定保留哪一个结果,并将其压入栈中。这样,栈中保存的元素将帮助我们正确计算最终结果。

解决代码

import java.util.Deque;import java.util.LinkedList;public class Solution {    public String parseTernary(String expression) {        if (expression == null || expression.isEmpty()) {            return "";        }        Deque
stack = new LinkedList<>(); for (int i = expression.length() - 1; i >= 0; i--) { char c = expression.charAt(i); if (!stack.isEmpty() && stack.peek() == '?') { stack.pop(); // Pop the question mark char first = stack.pop(); // Pop the left side of the ternary stack.pop(); // Pop the colon char second = stack.pop(); // Pop the right side of the ternary if (c == 'T') { stack.push(first); } else { stack.push(second); } } else { stack.push(c); } } return String.valueOf(stack.peek()); }}

代码解释

  • 初始化栈:使用Deque来实现栈,因为它可以方便地支持弹出元素。
  • 遍历字符串:从右到左遍历字符串中的每个字符。
  • 处理问号:当遇到问号时,弹出栈顶的问号、左边的表达式和右边的表达式。根据当前字符是T还是F,决定保留左边或右边的表达式,将其压入栈中。
  • 处理其他字符:将字符直接压入栈中。
  • 返回结果:栈中的顶部元素即为最终结果。
  • 这种方法确保了我们能够正确处理右结合的三元表达式,并在O(n)时间复杂度内完成计算,适用于字符串长度不超过10000的情况。

    转载地址:http://gmgyk.baihongyu.com/

    你可能感兴趣的文章
    sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
    查看>>
    ORCHARD 是什么?
    查看>>
    Struts2中使用Session的两种方法
    查看>>
    order by rand()
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>