Given a string representing arbitrarily nested ternary expressions, calculate the result of the expression. You can always assume that the given expression is valid and only consists of digits 0-9, ?, :, T and F (T and F represent True and False respectively).

Note:

The length of the given string is ≤ 10000.
Each number will contain only one digit.
The conditional expressions group right-to-left (as usual in most languages).
The condition will always be either T or F. That is, the condition will never be a digit.
The result of the expression will always evaluate to either a digit 0-9, T or F.
Example 1: Input: "T?2:3" Output: "2" Explanation: If true, then result is 2; otherwise result is 3.
Example 2: Input: "F?1:T?4:5" Output: "4" Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: "(F ? 1 : (T ? 4 : 5))" "(F ? 1 : (T ? 4 : 5))"
-> "(F ? 1 : 4)" or -> "(T ? 4 : 5)"
-> "4" -> "4"
Example 3: Input: "T?T?F:5:3" Output: "F" Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: "(T ? (T ? F : 5) : 3)" "(T ? (T ? F : 5) : 3)"
-> "(T ? F : 3)" or -> "(T ? F : 5)"
-> "F" -> "F"

My First Solution:

Use Stack and String operation, from the back of the string, find the first '?', push the right to stack. Depends on whether the char before '?' is 'T' or 'F', keep the corresponding string in the stack

 public class Solution {
public String parseTernary(String expression) {
Stack<String> st = new Stack<String>();
int pos = expression.lastIndexOf("?");
while (pos > 0) {
if (pos < expression.length()-1) {
String str = expression.substring(pos+1);
String[] strs = str.split(":");
for (int i=strs.length-1; i>=0; i--) {
if (strs[i].length() > 0)
st.push(strs[i]);
}
}
String pop1 = st.pop();
String pop2 = st.pop();
if (expression.charAt(pos-1) == 'T') st.push(pop1);
else st.push(pop2);
expression = expression.substring(0, pos-1);
pos = expression.lastIndexOf("?");
}
return st.pop();
}
}

Better solution, refer to https://discuss.leetcode.com/topic/64409/very-easy-1-pass-stack-solution-in-java-no-string-concat/2

No string contat/substring operation

 public String parseTernary(String expression) {
if (expression == null || expression.length() == 0) return "";
Deque<Character> 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 '?'
char first = stack.pop();
stack.pop(); //pop ':'
char second = stack.pop(); if (c == 'T') stack.push(first);
else stack.push(second);
} else {
stack.push(c);
}
} return String.valueOf(stack.peek());
}

Leetcode: Ternary Expression Parser的更多相关文章

  1. [LeetCode] Ternary Expression Parser 三元表达式解析器

    Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...

  2. LeetCode 439. Ternary Expression Parser

    原题链接在这里:https://leetcode.com/problems/ternary-expression-parser/description/ 题目: Given a string repr ...

  3. Ternary Expression Parser

    Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...

  4. PHP Cron Expression Parser ( LARAVEL )

       The PHP cron expression parser can parse a CRON expression, determine if it is due to run, calcul ...

  5. 【Resharper】C# “Simplify conditional ternary expression”

    #事故现场: 对某个对象做空值检测的时候,结合三元运算符给某变量赋值的时候,R#提示:"Simplify conditional ternary expression" : R#建 ...

  6. [LeetCode] Regular Expression Matching 正则表达式匹配

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

  7. LeetCode | Regular Expression Matching

    Regular Expression Matching Implement regular expression matching with support for '.' and '*'. '.' ...

  8. [leetcode]Regular Expression Matching @ Python

    原题地址:https://oj.leetcode.com/problems/regular-expression-matching/ 题意: Implement regular expression ...

  9. [LeetCode] Regular Expression Matching(递归)

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

随机推荐

  1. 【Oracle】oracle中快速判断某一日期是闰年或平年

    )),' then '平年' else '闰年' end as isLeapYear from dual 第一步:取日期的年初日期:第二步:年初日期增加一个月即概念2月:第三步:取概念2月的最后一天的 ...

  2. xcode8插件无法使用

    一,xcode8无法使用插件的问题 创建新的XcodeSigner代码证书,并执行"sudo codesign -f -s XcodeSigner /Applications/Xcode.a ...

  3. 【python】安装python第三方库lxml时,遇到问题:[ERROR: 'xslt-config' 不是内部或外部命令,也不是可运行的程序]

    一.概述 lxml介绍http://lxml.de/ 二.问题 ERROR: 'xslt-config' 不是内部或外部命令,也不是可运行的程序 三.解决方法 Scrapy在Windows上的安装笔记 ...

  4. Areas on the Cross-Section Diagram

    Areas on the Cross-Section Diagram  Aizu - ALDS1_3_D Areas on the Cross-Section Diagram 地域の治水対策として.洪 ...

  5. 20145205 《Java程序设计》第6周学习总结

    教材学习内容总结 -若要将数据从来源中取出,可以使用输入串流:若要将数据写入目的地,可以使用输出串流.在java中,输入串流代表对象为java.in.InputStream的实例:输出串流代表对象为j ...

  6. Java学习路线

    总体思路:由表及里,勤于实践,纵横交错,融会贯通 Java语言----->JDK----->Java虚拟机原理----->编译原理----->操作系统原理----->计算 ...

  7. 动态调用webservice(部分转载)

    动态调用webservice,做个笔记: public class WSHelper { /// < summary> /// 动态调用web服务 /// < /summary> ...

  8. canvas绘制二次贝塞尔曲线----演示二次贝塞尔四个参数的作用

    canvas中绘制二次贝塞尔曲线的方法为ctx.quadraticCurveTo(x1,y1,x2,y2); 四个参数分别为两个控制点的坐标.开始点即当前canvas中目前的点,如果想从指定的点开始, ...

  9. static{ }语句块详解

    static{}(即static块),会在类被加载的时候执行且仅会被执行一次,一般用来初始化静态变量和调用静态方法.举ge例子: public class Test { public static i ...

  10. 《UML大战需求分析》阅读笔记04

    在学习了前面的几种UML图并不能满足所有情况的建模,如当流程图涉及到多种角色,并且通过对多种角色交互展开时,顺序图才是不二选择.顺序图就如同中文语法的说话语言相似,描述的是一种事件发生的顺序.顺序图分 ...