Create No2.20. Valid Parentheses.md#2
Conversation
| class Solution { | ||
| public: | ||
| bool isValid(string s) { | ||
| stack<char> parenthese; |
| for(char c: s) { | ||
| if(c == '(' || c == '{' || c == '[') { |
There was a problem hiding this comment.
https://google.github.io/styleguide/cppguide.html#Formatting_Looping_Branching
リンク先はあくまでルールの例ですが、forやifの後ろは一つスペースを入れる方が良いと思います。
| } else if(!parenthese.empty() && c == ')' && parenthese.top() == '(') { | ||
| parenthese.pop(); | ||
| } else if(!parenthese.empty() && c == '}' && parenthese.top() == '{') { | ||
| parenthese.pop(); | ||
| } else if(!parenthese.empty() && c == ']' && parenthese.top() == '[') { | ||
| parenthese.pop(); |
There was a problem hiding this comment.
(小田さんのコメントにもありますが) もう少しまとめた方が見やすそうですしバグも起こしにくそうです。一箇所だけ parenthese.empty() の頭にある否定演算子を忘れた、とかありがちだと思うので。
There was a problem hiding this comment.
また、まとめることで拡張性という点でもメリットがあると思います。
もし判定する括弧がもっと増えた場合に修正箇所が少なく済みそうです。
| class Solution { | ||
| public: | ||
| bool isValid(string s) { | ||
| stack<char> parenthese; |
There was a problem hiding this comment.
実際に入るのは '(', '{', '[' の3種類だと思うので、 leftParentheses とか openParentheses とかの方がいいかもしれません
There was a problem hiding this comment.
odaさんがよくアドバイスされていますが、変数名に意味を持たせるのは大事だと感じます。
ここでは、fhiyoさんのご提案頂いた変数名にすることで、コードを読まなくてもこのstackに入るのはopen-bracketなんだな、ということが分かるようになり読み手の仕事が捗ると思います。
ご参考
https://discordapp.com/channels/1084280443945353267/1230079550923341835/1230201155619913728
| # step3 | ||
| 変数名をジェネリックプログラミングの観点から型名を除去 | ||
| if continue から if else に変更 | ||
| 条件判定で最初に empty を判定。理由は覚えていないが多分計算量を少しでも減らすため?代わりに可読性の低下 |
There was a problem hiding this comment.
ここは本当に計算量が減るのか、そうならばどういう原理で減るのか、調べてみるといいと思います。調べて分からない場合は講師役の方に質問してみるといいと思います。
レビューで指摘された箇所を修正したコード
| @@ -0,0 +1,30 @@ | |||
| # step4 | |||
| public: | ||
| bool isValid(string s) { | ||
| stack<char> open_parentheses; | ||
| unordered_map<char, char> match_parentheses; |
There was a problem hiding this comment.
|
|
||
| for(char c: s) { | ||
| if (c == '(' || c == '{' || c == '[') { | ||
| open_parentheses.push(c); |
https://leetcode.com/problems/valid-parentheses/description/