समस्या
Decide whether text can be split into a sequence of words from words. Words may be reused. Dynamic programming over prefixes solves it efficiently.
Implement can_break(text, words).
Input
text: Lowercase letters only. words: The dictionary; each word has 1–50 lowercase letters.
Output
Return true if a split exists.
सीमाएँ
0 ≤ length of text ≤ 5,000; 1 ≤ words ≤ 1,000
उदाहरण
इनपुट:
text = "applepenapple"
words = ["apple", "pen"]
अपेक्षित आउटपुट:
expected = True
इनपुट:
std::string text = "applepenapple";
std::vector<std::string> words = {"apple", "pen"};
अपेक्षित आउटपुट:
bool expected = true;
इनपुट:
string text = "applepenapple";
string[] words = new string[] {"apple", "pen"};
अपेक्षित आउटपुट:
bool expected = true;
व्याख्या
"apple" + "pen" + "apple", reusing "apple".
इनपुट:
text = "catsandog"
words = ["cats", "dog", "sand", "and", "cat"]
अपेक्षित आउटपुट:
expected = False
इनपुट:
std::string text = "catsandog";
std::vector<std::string> words = {"cats", "dog", "sand", "and", "cat"};
अपेक्षित आउटपुट:
bool expected = false;
इनपुट:
string text = "catsandog";
string[] words = new string[] {"cats", "dog", "sand", "and", "cat"};
अपेक्षित आउटपुट:
bool expected = false;
व्याख्या
Every split leaves "og" or "ando" unmatched: false.
कैसे हल करें
पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।
संकेत 1
अगर कोई earlier breakable point किसी dictionary word के साथ उसे reach कर ले, तो prefix breakable है.
संकेत 2
Positions पर dynamic programming तब अच्छी काम करती है जब आप word lengths या dictionary matches efficiently test करें.
संकेत 3
Empty text trivially breakable है, लेकिन repeated word reuse scan भर allowed रहना चाहिए.
अपेक्षित जटिलता
समय O(n^2), अतिरिक्त स्थान O(n)
संदर्भ
यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।