Skip to content

Commit fef4747

Browse files
committed
Add solution #439
1 parent d775c97 commit fef4747

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,7 @@
427427
436|[Find Right Interval](./solutions/0436-find-right-interval.js)|Medium|
428428
437|[Path Sum III](./solutions/0437-path-sum-iii.js)|Medium|
429429
438|[Find All Anagrams in a String](./solutions/0438-find-all-anagrams-in-a-string.js)|Medium|
430+
439|[Ternary Expression Parser](./solutions/0439-ternary-expression-parser.js)|Medium|
430431
440|[K-th Smallest in Lexicographical Order](./solutions/0440-k-th-smallest-in-lexicographical-order.js)|Hard|
431432
441|[Arranging Coins](./solutions/0441-arranging-coins.js)|Easy|
432433
442|[Find All Duplicates in an Array](./solutions/0442-find-all-duplicates-in-an-array.js)|Medium|
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 439. Ternary Expression Parser
3+
* https://leetcode.com/problems/ternary-expression-parser/
4+
* Difficulty: Medium
5+
*
6+
* Given a string expression representing arbitrarily nested ternary expressions,
7+
* evaluate the expression, and return the result of it.
8+
*
9+
* You can always assume that the given expression is valid and only contains digits,
10+
* '?', ':', 'T', and 'F' where 'T' is true and 'F' is false. All the numbers in the
11+
* expression are one-digit numbers (i.e., in the range [0, 9]).
12+
*
13+
* The conditional expressions group right-to-left (as usual in most languages), and
14+
* the result of the expression will always evaluate to either a digit, 'T' or 'F'.
15+
*/
16+
17+
/**
18+
* @param {string} expression
19+
* @return {string}
20+
*/
21+
var parseTernary = function(expression) {
22+
const stack = [];
23+
24+
for (let i = expression.length - 1; i >= 0; i--) {
25+
const char = expression[i];
26+
if (char !== ':' && char !== '?') {
27+
stack.push(char);
28+
} else if (char === '?') {
29+
const condition = expression[i - 1];
30+
const trueValue = stack.pop();
31+
const falseValue = stack.pop();
32+
stack.push(condition === 'T' ? trueValue : falseValue);
33+
i--;
34+
}
35+
}
36+
37+
return stack[0];
38+
};

0 commit comments

Comments
 (0)