139. Word Break#39
Conversation
| for (auto& word : words) { | ||
| TrieNode* node = root; | ||
| for (char c : word) { | ||
| if (!node->children.count(c)) |
|
|
||
| for (int i = 1; i <= s.size(); i++) { | ||
| for (int j = 0; j < i; j++) { | ||
| if (memo[j] && dict.contains(s.substr(j, i - j))) { |
There was a problem hiding this comment.
substrは恐らく文字列のコピーを作成すると思うので、なんとかしてコピーを作成しないようにするともうちょっとパフォーマンスがよくできるかもしれません。string_viewっていうのが使えたような気がします。
https://cpprefjp.github.io/reference/string_view/basic_string_view.html
There was a problem hiding this comment.
string_view 前に見たことがありましたが思い浮かびませんでした。ありがとうございます。
| bool wordBreak(std::string s, std::vector<std::string>& wordDict) { | ||
| std::unordered_set<std::string> dict(wordDict.begin(), wordDict.end()); | ||
| std::vector<bool> memo(s.size() + 1, false); | ||
| memo[0] = true; |
There was a problem hiding this comment.
is_breakable_untilみたいに明確に意味を持たせたほうがもしかしたら読みやすいかもしれないと思いました。自分は解いたことがあるのですらすら読めましたが、初見だとロジックをどう捉えればいいかのヒントがないので混乱しそうです。
| public: | ||
| bool wordBreak(std::string s, std::vector<std::string>& wordDict) { | ||
| std::unordered_set<std::string> dict(wordDict.begin(), wordDict.end()); | ||
| std::vector<bool> memo(s.size() + 1, false); |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
Hurukawa2121/leetcode#17 (comment)
| return false; | ||
| } | ||
|
|
||
| string strs = ""; |
There was a problem hiding this comment.
std::string はデフォルトコンストラクタで空文字に初期化されるため、 = "" は外しても良いと思います。
| return _helper(s, 0, dict, memo); | ||
| } | ||
| private: | ||
| int NOT_SEEN = -1; |
There was a problem hiding this comment.
定数は、プロセスの開始から終了まで値が変わらないことを保証し、かつインライン化されやすくするため、 static constexpr で定義することをお勧めいたします。
| private: | ||
| int NOT_SEEN = -1; | ||
|
|
||
| bool _helper( |
There was a problem hiding this comment.
C++ で private な関数の関数名の先頭に _ を付けるのは、あまり見ないように思いました。
こちらのコメントもご参照ください。
hemispherium/LeetCode_Arai60#12 (comment)
| public: | ||
| bool wordBreak(std::string s, std::vector<std::string>& wordDict) { | ||
| std::unordered_set<std::string> dict(wordDict.begin(), wordDict.end()); | ||
| std::vector<bool> memo(s.size() + 1, false); |
There was a problem hiding this comment.
使われ方を見るに memo であることは分かるので、can_break みたいな内容を名前に載せたいです。
添字と s の対応も分かりにくいので、名前に載せるなりコメントで補足するなりしたいです(s[:i_exclusive] がbreakできるかどうか、ですよね)。
問題
https://leetcode.com/problems/word-break/
次の問題
322. Coin Change