문제
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
앞부분이 breakable 하려면, 그보다 앞선 breakable 위치에서 사전 단어로 도달할 수 있어야 합니다.
힌트 2
위치별 DP가 잘 맞고, 단어 길이나 사전 매칭을 효율적으로 검사해야 합니다.
힌트 3
빈 텍스트는 자동으로 breakable이고, 같은 단어를 여러 번 재사용하는 것도 허용되어야 합니다.
예상 복잡도
시간 O(n^2), 추가 공간 O(n)
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.