Conversation
|
|
||
| public int evalRPN(String[] tokens) { | ||
| ArrayDeque<Integer> numStack = new ArrayDeque<>(); | ||
| Set<String> operators = new HashSet<>(Arrays.asList("*", "-", "+", "/")); |
There was a problem hiding this comment.
Set.of() のほうがシンプルに書けると思います。
https://docs.oracle.com/javase/jp/11/docs/api/java.base/java/util/Set.html
Set<String> operators = Set.of("*", "-", "+", "/");There was a problem hiding this comment.
ご確認ありがとうございます!
勉強になりますmm
| ```java | ||
| class Solution { | ||
| public int evalRPN(String[] tokens) { | ||
| Stack<Integer> stack = new Stack<>(); |
There was a problem hiding this comment.
ArrayDeque のほうが高速なため、 ArrayDeque を優先的に使用したほうが良いと思います。
https://docs.oracle.com/javase/jp/8/docs/api/java/util/ArrayDeque.html
このクラスは通常、スタックとして使われるときはStackよりも高速で、キューとして使われるときはLinkedListよりも高速です。
| Stack<Integer> stack = new Stack<>(); | ||
| for (String c : tokens) { | ||
| if (c.equals("+")) { | ||
| stack.push(stack.pop() + stack.pop()); |
There was a problem hiding this comment.
個人的には step1 のように 4 種類の演算を同じようなロジックで書いたほうが、読み手にとってパターンマッチングで読めるので読みやすく、かつ書き間違えにくいと思います。
| return dfs(tokenList); | ||
| } | ||
|
|
||
| private int dfs(List<String> tokens) { |
There was a problem hiding this comment.
関数名には、内部の実装の詳細を表す言葉より、入力に対してどのような処理を行うのか、どのような値を返すかが分かるものを付けたほうが、読み手にとって分かりやすいと思います。
parse() はいかがでしょうか?これなら、入力データに対して構文解析を行い、その結果を返すことが読み手に伝わりやすいと思います。
| ArrayDeque<Integer> stack = new ArrayDeque<>(); | ||
| Set<String> operators = new HashSet<>(Arrays.asList("-", "+", "*", "/")); | ||
|
|
||
| for(String token : tokens) { |
There was a problem hiding this comment.
for 文の後にスペースを空けることをおすすめします。
参考までにスタイルガイドへのリンクを貼ります。
https://google.github.io/styleguide/javaguide.html#s4.6.2-horizontal-whitespace
Separating any keyword, such as if, for or catch, from an open parenthesis (() that follows it on that line
上記のスタイルガイドは唯一絶対のルールではなく、複数あるスタイルガイドの一つに過ぎないということを念頭に置くことをお勧めします。また、所属するチームにより何が良いとされているかは変わります。自分の中で良い書き方の基準を持ちつつ、チームの平均的な書き方で書くことをお勧めいたします。
| if (operators.contains(token)) { | ||
| int rightNum = numStack.pollLast(); | ||
| int leftNum = numStack.pollLast(); | ||
| numStack.add(this.calculateFromOperator(leftNum, rightNum, token)); |
https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that: