1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| #include <iostream> #include <vector> #include <string> #include <unordered_set> #include <algorithm> using namespace std;
class Solution_0 { public: bool wordBreak(string s, vector<string>& wordDict) { int n = s.size(); vector<bool> f(n+1, false); f[0] = true;
for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { auto it = find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)); if (f[j] && wordDict.end() != it) { f[i] = true; break; } } }
return f[n]; } };
class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { unordered_set<string> set(wordDict.begin(), wordDict.end()); int n = s.size(); vector<bool> f(n+1, false); f[0] = true;
for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { if (f[j] && set.count(s.substr(j, i - j))) { f[i] = true; break; } } }
return f[n]; } };
void printArray(const vector<string>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << "\"" << nums[i] << "\""; if (i != nums.size() - 1) cout << ","; } cout << "]"; }
int main() { Solution solution; vector<string> s_cases = { "leetcode", "applepenapple", "catsandog" }; vector<vector<string>> wordDict_cases = { {"leet", "code"}, {"apple", "pen"}, {"cats", "dog", "sand", "and", "cat"} };
for (int i = 0; i < s_cases.size(); i++) { string s = s_cases[i]; vector<string> wordDict = wordDict_cases[i]; bool result = solution.wordBreak(s, wordDict);
cout << "Input: s = " << s << ", wordDict = "; printArray(wordDict); cout << endl; cout << "Output: " << (result ? "true" : "false") << endl; }
return 0; }
|