어려움 2명 해결 정답률 66.7%

Word Break

Decide whether text can be split into dictionary words.

배우게 될 내용

  • Mark which prefixes can be split
  • Use a set for fast dictionary lookups
  • Build a boolean DP over positions

문제

번역본 보기

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

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에 맞게 수정되었습니다. 위의 설명과 제약 조건을 기준으로 풀어 주세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 ННикита Python 806 ms - 5/5 코드 보기
2 KKKaneki Ken Python 851 ms - 2/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 풀이

스포일러: 아래에 전체 풀이 2개가 있습니다 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.