LeetCode 439. Ternary Expression Parser
原题链接在这里:https://leetcode.com/problems/ternary-expression-parser/description/
题目:
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
TorF. That is, the condition will never be a digit. - The result of the expression will always evaluate to either a digit
0-9,TorF.
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"
题解:
从后往前扫输入的string. 把char 放入stack中. 当扫过了'?', 就知道需要开始判断了.
从stack中弹出两个数,判断后的数放回stack中.
Time Complexity: O(n). n = expression.length();
Space: O(n).
AC Java:
class Solution {
public String parseTernary(String expression) {
if(expression == null || expression.length() == 0){
return expression;
}
Stack<Character> stk = new Stack<Character>();
for(int i = expression.length()-1; i>=0; i--){
char c = expression.charAt(i);
if(!stk.isEmpty() && stk.peek()=='?'){
stk.pop(); // '?'
char first = stk.pop();
stk.pop(); // ':'
char second = stk.pop();
if(c == 'T'){
stk.push(first);
}else{
stk.push(second);
}
}else{
stk.push(c);
}
}
return String.valueOf(stk.peek());
}
}
Track the first string and second string separated by the corresponding " : ".
Based on the true or false, continue DFS on the corresponding string.
Time Complexity: O(n^2). n = expression.length().
Space: O(n).
AC Java:
class Solution {
public String parseTernary(String expression) {
if(expression.length() == 1){
return expression;
}
int indexQuestion = expression.indexOf("?");
boolean flag = expression.charAt(0) == 'T' ? true : false;
int count = 0;
int start = indexQuestion+1;
while(expression.charAt(start) != ':' || count != 0){
if(expression.charAt(start) == '?'){
count++;
}else if(expression.charAt(start) == ':'){
count--;
}
start++;
}
String first = expression.substring(indexQuestion+1, start);
String second = expression.substring(start+1);
return parseTernary(flag ? first : second);
}
}
LeetCode 439. Ternary Expression Parser的更多相关文章
- [LeetCode] Ternary Expression Parser 三元表达式解析器
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...
- Leetcode: Ternary Expression Parser
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...
- Ternary Expression Parser
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...
- [LeetCode] Parse Lisp Expression 解析Lisp表达式
You are given a string expression representing a Lisp-like expression to return the integer value of ...
- PHP Cron Expression Parser ( LARAVEL )
The PHP cron expression parser can parse a CRON expression, determine if it is due to run, calcul ...
- leetcode 10 Regular Expression Matching(简单正则表达式匹配)
最近代码写的少了,而leetcode一直想做一个python,c/c++解题报告的专题,c/c++一直是我非常喜欢的,c语言编程练习的重要性体现在linux内核编程以及一些大公司算法上机的要求,pyt ...
- 【Resharper】C# “Simplify conditional ternary expression”
#事故现场: 对某个对象做空值检测的时候,结合三元运算符给某变量赋值的时候,R#提示:"Simplify conditional ternary expression" : R#建 ...
- 【LeetCode】385. Mini Parser 解题报告(Python)
[LeetCode]385. Mini Parser 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/mini-parser/ ...
- LeetCode (10): Regular Expression Matching [HARD]
https://leetcode.com/problems/regular-expression-matching/ [描述] Implement regular expression matchin ...
随机推荐
- 【Python爬虫案例学习2】python多线程爬取youtube视频
转载:https://www.cnblogs.com/binglansky/p/8534544.html 开发环境: python2.7 + win10 开始先说一下,访问youtube需要那啥的,请 ...
- Python有用的内置函数divmod,id,sorted,enumerate,input,oct,eval,exec,isinstance,ord,chr,filter,vars,zip
divmod(a, b) 函数接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a // b, a % b) id() 函数用于获取对象的内存地址. sorted(iterable, key ...
- Kafka启用SASL_PLAINTEXT动态配置JAAS文件的几种方式
Kafka是广泛使用消息服务,很多情况下关于认证部分我都是默认的配置,也就是不需要用户名/密码,也不配置证书.在内网或者在项目组内部可以,但是设计的跨部门时一般处于安全考虑都需要加上认证,防止kafk ...
- P1108 低价购买 (DP)
题目 P1108 低价购买 解析 这题做的我身心俱惫,差点自闭. 当我WA了N发后,终于明白了这句话的意思 当二种方案"看起来一样"时(就是说它们构成的价格队列一样的时候),这2种 ...
- aria config
aria2c --conf-path=aria2.conf mine: max-concurrent-downloads=5 continue=true max-overall-download-li ...
- el-table单元格样式更改
前几天遇到一个关于el-table表格样式的问题一直没解决 因为在el-table-column加样式并不生效所以更改起来比较麻烦 后来了看来element官方文档和在一些关于此方面的博客,使用了一个 ...
- Java框架之MyBatis框架(一)
一.框架介绍: MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动.创建connection.创建sta ...
- AudioToolbox--AudioQueue实现流播放接口
AudioMedia_ios.h // // AudioMedia_ios.h // mmsplayer // // Created by Weiny on 12-4-4. // Copyri ...
- PHP 将json的int类型转换为string类型 解决php bigint转科学计数法的问题
/** * 将json的int类型转换为string类型 * @param $str * @param int $minLength 最小的转换位数,即只有大于等于这个长度的数字才会被转换为字符串 * ...
- SpringBoot2.x项目初始化
1. 项目初始化说明 使用SpringBoot生成器 修改application.properties为application.yml 启动运行SpringBoot项目 2. 初始化项目 Spring ...