Leetcode: Ternary Expression Parser
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的更多相关文章
- [LeetCode] Ternary Expression Parser 三元表达式解析器
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...
- LeetCode 439. Ternary Expression Parser
原题链接在这里:https://leetcode.com/problems/ternary-expression-parser/description/ 题目: Given a string repr ...
- Ternary Expression Parser
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...
- PHP Cron Expression Parser ( LARAVEL )
The PHP cron expression parser can parse a CRON expression, determine if it is due to run, calcul ...
- 【Resharper】C# “Simplify conditional ternary expression”
#事故现场: 对某个对象做空值检测的时候,结合三元运算符给某变量赋值的时候,R#提示:"Simplify conditional ternary expression" : R#建 ...
- [LeetCode] Regular Expression Matching 正则表达式匹配
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
- LeetCode | Regular Expression Matching
Regular Expression Matching Implement regular expression matching with support for '.' and '*'. '.' ...
- [leetcode]Regular Expression Matching @ Python
原题地址:https://oj.leetcode.com/problems/regular-expression-matching/ 题意: Implement regular expression ...
- [LeetCode] Regular Expression Matching(递归)
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
随机推荐
- VMware下虚拟机的转移
将虚拟机文件夹整个拷贝到另一台电脑上: 打开.vmx文件 打开即可: 注意:Mac系统的虚拟机要先用unlocker206破解,才能运行OS系统.
- poj1155 TELE (树上的背包)
题目链接:http://poj.org/problem?id=1155 题意:给定一棵树,1为根结点表示电视台,有m个叶子节点表示客户,有n-m-1个中间节点表示中转站,每条树边有权值.现在要在电视台 ...
- 2012 Multi-University #7
最短路+拆点 A As long as Binbin loves Sangsang 题意:从1走到n,每次都是LOVE,问到n时路径是连续多个"LOVE"的最短距离.秀恩爱不想吐槽. 分析:在普通的最 ...
- 关于activity的生命周期的随笔
在activity的生命周期中,我总是容易混淆,onstart和on resume ,on pause和onstop 原来这个都是一对的. onstart 对应 onstop ,意义在于使页面显示出来 ...
- 给MySQL增加mysql-udf-http和mysql-udf-json自定义函数,让MySQL有调用http接口和查询直接回JSON的能力
1.安装mysql-udf-httpyum install -y libcurl*下载地址:http://pan.baidu.com/s/1nuYZqR3tar zxvf mysql-udf-http ...
- mysql错误汇总
1,mysql报Fatal error encountered during command execution的解决办法 连接字符串里加上 Allow User Variables=True 解决. ...
- PHP+Zend 输出时中文乱码问题
1.把输入的格式改成 echo iconv("GB2312","UTF-8",'我爱PHP'); 2.其他的方法,还不会用,有待完善........
- 动态生成linearLayout
LinearLayout linearLayout=new LinearLayout(this); linearLayout.setOrientation(LinearLayout.VERTICAL) ...
- spring的显示装配bean(1)------通过XML文件装配
1:spring环境的简单搭建 (1)导入spring相关的jar包. 2:准备要进行装配的Java类 这里给出两个举例类 (1) (2) 3:配置XML文件 (1)在配置文件的顶部声明多个XML模式 ...
- 记一次程序排错与std::getline
今天忙活了半个下午,查找正式环境上面一个程序的问题.这个程序的作用是监控文件夹,处理每一个文件,分析每个文件的每行记录,然后将这个文件拆分成两个结果文件投放到另外两个不同的目录下面去,当处理完这个文件 ...