문제
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
A prefix is breakable if some earlier breakable point reaches it with a dictionary word.
힌트 2
Dynamic programming over positions works well when you test word lengths or dictionary matches efficiently.
힌트 3
Empty text is trivially breakable, but repeated word reuse should remain allowed throughout the scan.
예상 복잡도
O(n^2) time, O(n) extra space
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제약 조건을 기준으로 풀어 주세요.