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. Android源码目录结构详解(转载)

    转自:http://blog.csdn.net/xiangjai/article/details/9012387 在学习Android的过程中,学习写应用还好,一开始不用管太多代码,直接调用函数就可以 ...

  2. NOIP2009分数线划定【B004】

    [B004]分数线划定[难度B]—————————————————————————————————————————————————————————————————————————— [题目要求] 世博 ...

  3. CentOS6.7安装Python3.4

    1.下载Python3.4安装包 wget https://www.python.org/ftp/python/3.4.4/Python-3.4.4.tgz 2.解压.编译.安装 .tgz cd Py ...

  4. SpringMVC介绍之Validation

    对于任何一个应用而言在客户端做的数据有效性验证都不是安全有效的,这时候就要求我们在开发的时候在服务端也对数据的有效性进行验证.SpringMVC自身对数据在服务端的校验有一个比较好的支持,它能将我们提 ...

  5. 一个叫vtysh的命令行shell

    目前的工作就是在这个叫vtysh的工具上进行修改,终极目的是把它作为一个代替shell的东西.以此来屏蔽用户和系统之间的接触,减少用户对系统的操作权限.

  6. 阿里云SLB双机IIS多站点负载均衡部署笔记

    首先SLB是通过局域网与ECS链接 ECS1服务器 test文件夹增加index.html test1文件夹增加index.html 设置ECS1服务器(130)IIS test站点 设置test主机 ...

  7. Java 中多条件排序

    Collections.sort(ghEntityList, new Comparator<GongHuiEntity>() { @Override public int compare( ...

  8. 【iCore3应用开发平台】发布 iCore3 应用开发平台出厂代码rev0.0.5

    iCore3开发平台固件版本信息 =============================================================[stm32f407]:iCore3 ARM ...

  9. requestAnimationFrame与setInterval,setTimeout

    自打学习canvas动画以来,都说requestAnimationFrame好,就一直用,也没觉得有什么太过于特殊的地方,直到刚才,在写完前面的"小球碰撞墙壁----干掉误差"之后 ...

  10. HTML/Elements/base

    https://www.w3.org/wiki/HTML/Elements/base HTML/Elements/base < HTML‎ | Elements   List of Elemen ...