Conversation
0020_Valid_Parentheses/solution.md
Outdated
|
|
||
| ```java | ||
| class Solution { | ||
| public static final Set<Character> OPEN_BRACKETS = Set.of( |
There was a problem hiding this comment.
他のクラスから参照されない定数は private にしたほうがよいと思います。
| ```java | ||
| class Solution { | ||
| public boolean isValid(String s) { | ||
| Deque<Character> stack = new ArrayDeque<>(); |
There was a problem hiding this comment.
念のため知識面を確認させてください。 LinkedList を使用する場合と比べ、 ArrayDeque はどのような利点がありますか?
There was a problem hiding this comment.
正直、stackの実装にはArrayDequeを使うという形で機械的に考えていたので、LinkedListで実装できるという発想すらなかったですね。。
ご質問に対して調べずに回答すると、ArrayDequeの方がLinkedListよりメモリ効率が良いと思います。LinkedListは各要素が隣のノードの参照を持つため1要素のメモリ消費が大きいのではないかと思います。
There was a problem hiding this comment.
ありがとうございます。メモリ効率についてはその通りなのですが、 ArrayDeque より高速であるという点のほうが重要だと思います。詳しくは Javadoc をご覧ください。
https://docs.oracle.com/javase/jp/8/docs/api/java/util/ArrayDeque.html
疑問に思ったときに公式ドキュメントを読む癖をつけることをお勧めいたします。
There was a problem hiding this comment.
公式ドキュメントに明記してあるのですね。読む癖をつけようと思います。
0020_Valid_Parentheses/solution.md
Outdated
| '(', '[', '{' | ||
| ); | ||
|
|
||
| public static final Map<Character, Character> BRACKET_CLOSE_OPEN = Map.of( |
There was a problem hiding this comment.
キーを開きカッコ、値を閉じカッコにした Map のみ持たせる方法もあります。
if (BLACKET_OPEN_CLOSE.containsKey(c)) {
stack.push(c);
}
else if (stack.isEmpty())
{
return false;
}
else if (BLACKET_OPEN_CLOSE.get(stack.getLast()) == c)
{
stack.pop();
}
else
{
return false;
}There was a problem hiding this comment.
なるほど、たしかにこの書き方であればいけますね。ありがとうございます。
|
|
||
| for (char c : s.toCharArray()) { | ||
| if (OPEN_BRACKETS.contains(c)) { | ||
| stack.push(c); |
There was a problem hiding this comment.
ありがとうございます。たしかに後続の判定必要ないのでその方がいいですね。
0020_Valid_Parentheses/solution.md
Outdated
| if (OPEN_BRACKETS.contains(c)) { | ||
| stack.push(c); | ||
| } | ||
| if (BRACKET_CLOSE_OPEN.containsKey(c)) { |
There was a problem hiding this comment.
これは括弧でないものが入ってきたとしたら、その字は何もしないで流すコードになっていますが、意図的でしょうか。異常な入力への対応は、一応念頭に置いてください。何かをする必要がかならずあるわけではないです。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.jdtk9v35bca4
個人的には、条件をひっくり返して、continue にして下のインデントを下げます。
There was a problem hiding this comment.
いえ、意図できていませんでした。LeetCodeを解く際、流れてくるデータの内容は保証されているという前提で解いてしまっておりました。あるいは、データが変更されたとしたらその時に変更してしまえばいいくらいに考えてた気がします。
あくまで大局観や想像力を養うという目的だと思うので、LeetCodeのルールに囚われず念頭に置いて取り組むようにします。
問題
20. Valid Parentheses
言語
Java
次の問題
276. Paint Fence