439. Ternary Expression Parser
来源:互联网 发布:佳能打印机安装软件 编辑:程序博客网 时间:2024/06/17 21:57
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
orF
. That is, the condition will never be a digit. - The result of the expression will always evaluate to either a digit
0-9
,T
orF
.
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"queue存储,从后向前遍历字符串,遇到peek = ?,pop出来?,pop出来first,pop出来:,pop出来second。如果当前是T,push first,否则push second。代码如下:
public class Solution { public String parseTernary(String expression) { if (expression == null || expression.length() == 0) { return ""; } Deque<Character> stack = new LinkedList<Character>(); for (int i = expression.length() - 1; i >= 0; i --) { char ch = expression.charAt(i); if (!stack.isEmpty() && stack.peek() == '?') { stack.pop(); //'?' char first = stack.pop(); stack.pop(); //':' char second = stack.pop(); stack.push(ch == 'T'? first: second); } else { stack.push(ch); } } return stack.pop() + ""; }}
阅读全文
0 0
- 439. Ternary Expression Parser
- 439. Ternary Expression Parser
- leetcode 439. Ternary Expression Parser
- LeetCode 439. Ternary Expression Parser
- Leetcode 439. Ternary Expression Parser (递归,栈)
- [Leetcode] 439. Ternary Expression Parser 解题报告
- Ternary Expression
- Convert a Ternary expression to a Binary tree structure
- v8::internal::Parser中的Expression解析
- 表达式剖析器(THE EXPRESSION PARSER)
- v8::internal::Parser中的Expression解析
- Ternary Password
- Ternary Calculation
- Ternary Password
- Ternary Tree
- Ternary Calculation
- [[ expression ]]
- expression
- jquery常用属性
- Sorgs天气app开发
- plsql 登录后,提示数据库字符集(AL32UTF8)和客户端字符集(ZHS16GBK)不一致
- 计算机硬件基础知识
- Unity3D C#中GUI.TextField的传递
- 439. Ternary Expression Parser
- Linux(CentOS)下,下载安装Nginx并配置
- ubuntu14.04 system-monitor-Indicator打不开
- 解决ubuntu16.04上网无法解析DNS问题
- zigbee网络地址与mac地址的相互转换
- python学习笔记--groupby
- Centos 7不能上网,Job for iptables.service failed because the control process exited with error code.
- 常用电阻阻值
- 十分钟搞定pandas