|
51 | 51 | */
|
52 | 52 | public class _439 {
|
53 | 53 |
|
54 |
| - /**Below is my original solution, but looking at Discuss, a more concise way is to use just one stack, process it from right to left, |
55 |
| - * example: https://discuss.leetcode.com/topic/64409/very-easy-1-pass-stack-solution-in-java-no-string-concat*/ |
56 |
| - |
57 |
| - public String parseTernary(String expression) { |
58 |
| - Deque<Character> stack = new ArrayDeque<>(); |
59 |
| - Deque<Character> tmpStack = new ArrayDeque<>(); |
60 |
| - for (char c : expression.toCharArray()) { |
61 |
| - stack.addFirst(c); |
62 |
| - } |
63 |
| - while (!stack.isEmpty()) { |
64 |
| - if (stack.peek() != '?') { |
65 |
| - tmpStack.addFirst(stack.pollFirst()); |
66 |
| - } else { |
67 |
| - char char1 = tmpStack.removeFirst(); |
68 |
| - tmpStack.removeFirst();//remove ':' |
69 |
| - char char2 = tmpStack.removeFirst(); |
70 |
| - stack.removeFirst();//remove '?' |
71 |
| - char judge = stack.removeFirst(); |
72 |
| - tmpStack.addFirst(judge == 'T' ? char1 : char2); |
73 |
| - while (!tmpStack.isEmpty()) { |
74 |
| - stack.addFirst(tmpStack.pollFirst()); |
75 |
| - } |
| 54 | + public static class Solution1 { |
| 55 | + /** |
| 56 | + * Below is my original solution, but looking at Discuss, a more concise way is to use just one |
| 57 | + * stack, process it from right to left, example: https://discuss.leetcode.com/topic/64409/very-easy-1-pass-stack-solution-in-java-no-string-concat |
| 58 | + */ |
| 59 | + |
| 60 | + public String parseTernary(String expression) { |
| 61 | + Deque<Character> stack = new ArrayDeque<>(); |
| 62 | + Deque<Character> tmpStack = new ArrayDeque<>(); |
| 63 | + for (char c : expression.toCharArray()) { |
| 64 | + stack.addFirst(c); |
76 | 65 | }
|
77 |
| - if (stack.size() == 1) { |
78 |
| - break; |
| 66 | + while (!stack.isEmpty()) { |
| 67 | + if (stack.peek() != '?') { |
| 68 | + tmpStack.addFirst(stack.pollFirst()); |
| 69 | + } else { |
| 70 | + char char1 = tmpStack.removeFirst(); |
| 71 | + tmpStack.removeFirst();//remove ':' |
| 72 | + char char2 = tmpStack.removeFirst(); |
| 73 | + stack.removeFirst();//remove '?' |
| 74 | + char judge = stack.removeFirst(); |
| 75 | + tmpStack.addFirst(judge == 'T' ? char1 : char2); |
| 76 | + while (!tmpStack.isEmpty()) { |
| 77 | + stack.addFirst(tmpStack.pollFirst()); |
| 78 | + } |
| 79 | + } |
| 80 | + if (stack.size() == 1) { |
| 81 | + break; |
| 82 | + } |
79 | 83 | }
|
| 84 | + return Character.toString(stack.removeFirst()); |
80 | 85 | }
|
81 |
| - return Character.toString(stack.removeFirst()); |
82 | 86 | }
|
83 | 87 |
|
84 | 88 | }
|
0 commit comments