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. checkedListBox

    checkedListBox一键删除多个选中items private void button3_Click(object sender, EventArgs e) { ; i < checke ...

  2. iOS typedef NS_ENUM 与 NSString

    //在头文件中声明 typedef NS_ENUM(NSUInteger, TransactionState) { TransactionOpened, TransactionPending, Tra ...

  3. ggplot2包的说明文档[分享]

  4. erlang mac os 10.9 卸载脚本

    #!/bin/bash if [ "$(id -u)" != "0" ]; then echo "Insufficient permissions. ...

  5. sqlserver2008 日志文件压缩的完整解决办法

    在项目中数据库创建了一个本地发布和订阅,造成日志文件飞涨,想把日志文件缩小. 1:最初使用了最常用的方法: USE [master] GO ALTER DATABASE 库名 SET RECOVERY ...

  6. 全新的博客之旅&大学生活

    博客之旅: 刚刚申请了博客,感觉非常兴奋,整个人都变得有精神了. 想来几个月之前看到奇奇申了博客,在上面写文章,写各种解题报告,心里就好羡慕,好希望将来有一天,也能有一个属于自己的博客.由于之前课业压 ...

  7. 通过hexo+NexT构建静态博客

    一般的教程网上有很多,主要讲下我遇到的问题以及解决方法: 一.hexo建立的文档无法上传github deploy: type: git repository: https://github.com/ ...

  8. stl循环删除

    struct st_data { st_data(int i) : id(i) {} int id; }; 对于STL标准序列容器vector/deque/list(以vector为例) 当我们需清空 ...

  9. 实战Java虚拟机之三“G1的新生代GC”

    今天开始实战Java虚拟机之三:“G1的新生代GC”. 总计有5个系列 实战Java虚拟机之一“堆溢出处理” 实战Java虚拟机之二“虚拟机的工作模式” 实战Java虚拟机之三“G1的新生代GC” 实 ...

  10. 【emWin】例程六:设置颜色

    实验指导书及代码包下载: 链接:http://pan.baidu.com/s/1eSidREy 密码:ru3c 实验现象: