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 ...
随机推荐
- android解析json
android2.3提供的json解析类 android的json解析部分都在包org.json下,主要有以下几个类: JSONObject:可以看作是一个json对象 JSONStringer:js ...
- Node.js-Socket.IO【1】-身份验证
Websocket身份验证失败的时候,希望向前台传输错误信息,但是Socket.IO目前最新版本1.4.6在后台使用 next(new Error('unauthorization')); 前端的代码 ...
- 在DrawingVisual上绘制圆形的进度条,类似于IOS系统风格。
1.说明:在WPF中,文件下载时需要显示下载进度,由于系统自带的条型进度条比较占用空间,改用圆形的进度条,需要在DrawingVisual上呈现. 运行的效果如图: private Point Get ...
- JavaScript函数表达式
函数表达式的基本语法形式 var functionName = function(arguments){ //函数体 } 递归建议 我们通过例子来一步步说明,递归的最佳实现方式.下面是普通递归调用的例 ...
- java实现a+b的多重输入
import java.util.Scanner; public class hello { public static void main(String[] args) { Scanner cin ...
- ZeroMQ接口函数之 :zmq_sendmsg – 从一个socket上发送一个消息帧
ZeroMQ 官方地址 :http://api.zeromq.org/4-1:zmq-sendmsg zmq_sendmsg(3) ØMQ Manual - ØMQ/4.1.0 Name ...
- 如何在VS2012中使用IL Disassembler中查看项目编译生成的程序集
2016-05-26 11:48:46 测试的WPF项目 MainWindow.xaml代码 MainWindow.xaml.cs 代码 在学习WPF的时候,想验证:删除MainWindow.xaml ...
- jQuery常用插件
jQuery UI插件简介: jQuery UI是以 jQuery 为基础的开源 JavaScript 网页用户界面代码库.包含底层用户交互.动画.特效和可更换主题的可视控件.我们可以直接用它来构建具 ...
- 第一章-第一题(小学生四则运算)--By郭青云
1.项目需求 a) 除了整数以外,还要支持真分数的四则运算. (例如: 1/6 + 1/8 = 7/24) b) 让程序能接受用户输入答案,并判定对错. 最后给出总共 对/错 的数量. c) 逐步扩 ...
- C#解析HTML
第一种方法:用System.Net.WebClient下载Web Page存到本地文件或者String中,用正则表达式来分析.这个方法可以用在Web Crawler等需要分析很多Web Page的应用 ...