From dd35b5f35b131a72526aa34f5048f82d10d5db9a Mon Sep 17 00:00:00 2001 From: colorbox Date: Tue, 30 Jun 2026 14:12:41 +0900 Subject: [PATCH] 139. Word Break https://leetcode.com/problems/word-break/description/ --- 139/step1.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 139/step2.cpp | 20 ++++++++++++++++++++ 139/step3.cpp | 17 +++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 139/step1.cpp create mode 100644 139/step2.cpp create mode 100644 139/step3.cpp diff --git a/139/step1.cpp b/139/step1.cpp new file mode 100644 index 0000000..b4d7d72 --- /dev/null +++ b/139/step1.cpp @@ -0,0 +1,38 @@ +/* +Time: 20:30 + +Time Complexity: O(n * m *l) (n: sの長さ, m: wordDictの長さ, l: wordDictの単語平均長) +Space Complexity: O(1) + +全探索的な解法はすぐに思いついたが、細かいミスで時間をロスした +C++の文字列操作関連でいい感じのメソッドを知っていればそれを使用したが、一旦手慣れたループで対応 +*/ + +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + vector matched_index(s.size(), false); + for (int i = 0; i < s.size(); ++i) { + if (i > 0 && matched_index[i - 1] == false) { + continue; + } + for (string word : wordDict) { + if (word[0] != s[i]) { + continue; + } + for (int j = 0; j < word.size(); ++j) { + if (i + j >= s.size()) { + break; + } + if (s[i + j] != word[j]) { + break; + } + if (j == word.size() - 1) { + matched_index[i + j] = true; + } + } + } + } + return matched_index.back(); + } +}; diff --git a/139/step2.cpp b/139/step2.cpp new file mode 100644 index 0000000..f115d67 --- /dev/null +++ b/139/step2.cpp @@ -0,0 +1,20 @@ +/* +string_viewを使用する方法もあったが、変数を増やすよりもcompareで直接比較したほうがシンプル +*/ +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + vector segmented_indexes(s.size(), false); + for (int i = 0; i < s.size(); ++i) { + if (i > 0 && segmented_indexes[i - 1] == false) { + continue; + } + for (const string& word: wordDict) { + if (!s.compare(i, word.size(), word)) { + segmented_indexes[i + word.size() - 1] = true; + } + } + } + return segmented_indexes.back(); + } +}; diff --git a/139/step3.cpp b/139/step3.cpp new file mode 100644 index 0000000..4ac6d78 --- /dev/null +++ b/139/step3.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + vector segmented_indexes(s.size()); + for (int i = 0; i < s.size(); ++i) { + if (i > 0 && !segmented_indexes[i - 1]) { + continue; + } + for (const string& word : wordDict) { + if (s.compare(i, word.size(), word) == 0) { + segmented_indexes[i + word.size() - 1] = true; + } + } + } + return segmented_indexes.back(); + } +};