어려움 0명 해결 정답률 0%

Word Break

Decide whether text can be split into dictionary words.

배우게 될 내용

  • 나눌 수 있는 접두사 표시하기
  • 집합으로 사전을 빠르게 조회하기
  • 위치에 대한 불리언 DP 만들기

문제

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

예시

예시 1
입력:
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".

예시 2
입력:
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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.