139. Word Break

2024. 11. 11. 23:21·Algorithm/LeetCode
목차
  1. 문제
  2. Solution
  3. 회고

문제

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

Example 1:

Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false

Constraints:

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.

Solution

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> wordSet = new HashSet<>(wordDict);  // wordDict를 Set으로 만들어서 탐색 시간을 줄임
        int n = s.length();
        // dp[i]: 처음부터 i까지 분할 가능한지(wordDict에 존재하는지)
        boolean[] dp = new boolean[n];

        //dp 초기화
        for(int i=0;i<n;i++) {
            String sub = s.substring(0,i+1);
            if(wordSet.contains(sub)) {
                dp[i]=true;
            }
        }

        for(int i=0;i<n;i++) {
            if(dp[i]) {
                for(int j=i+1;j<n;j++) {
                    String sub = s.substring(i+1,j+1);
                    if(wordSet.contains(sub)) {
                        dp[j]=true;
                    }
                }
            }
        }

        return dp[n-1];
    }
}

회고

항상 DP 문제를 풀 때마다 dp[i] 정의에 어려움을 겪는다.

 

길이 n의 문자열 s에 대해, dp[i]는 s의 처음부터 i까지의 부분 문자열을 wordDict의 단어들로 분할할 수 있는지를 나타낸다.

 

문자열 s의 각 위치 i에 대해, dp[i]가 true일 때, i 이후의 위치 j까지의 부분 문자열이 wordDict에 존재하면 dp[j]를 true 설정한다. 이렇게 하면 s의 처음부터 끝까지의 각 부분 문자열이 wordDict의 단어들로 분할 가능한지 확인할 수 있다.

 

초기화를 단계에서

        for(int i=0;i<n;i++) {
            String sub = s.substring(0,i+1);
            if(wordSet.contains(sub)) {
                dp[i]=true;
            }
        }

s의 첫 인덱스부터 i 인덱스까지의 부분 문자열이 wordDict에 포함되는지 확인하는 작업을 수행했다. 이를 통해 문자열의 시작 구간이 wordDict의 단어들로 분리될 수 있는지를 설정하여, 이후 DP 연산의 기반을 마련했다.

'Algorithm > LeetCode' 카테고리의 다른 글

377. Combination Sum IV  (0) 2024.11.17
1143. Longest Common Subsequence  (0) 2024.11.16
300. Longest Increasing Subsequence  (0) 2024.11.07
322. Coin Change  (0) 2024.11.04
70. Climbing Stairs  (0) 2024.10.31
  1. 문제
  2. Solution
  3. 회고
'Algorithm/LeetCode' 카테고리의 다른 글
  • 377. Combination Sum IV
  • 1143. Longest Common Subsequence
  • 300. Longest Increasing Subsequence
  • 322. Coin Change
사랑우주인
사랑우주인
  • 사랑우주인
    lovelyAlien
    사랑우주인
  • 전체
    오늘
    어제
  • 글쓰기
    관리
    • 분류 전체보기 (208)
      • Programming (4)
        • Spring (28)
        • Java (46)
        • JPA (2)
        • 디자인 패턴 (5)
        • 개발&아키텍처 (0)
      • Network (13)
      • OS (19)
      • Database (1)
      • Kubernetes (0)
      • Kafka (2)
      • Algorithm (49)
        • BaekJoon (1)
        • Programmers (19)
        • Algorithm (5)
        • Socar (2)
        • LeetCode (19)
      • Interview (2)
      • Issues (2)
      • DotJoin (1)
      • Git (4)
      • 독서 (3)
      • 끄적끄적 (1)
      • 외부활동 (26)
        • 항해플러스 (2)
        • JSCODE 네트워크 (19)
        • JSCODE 자바 (5)
      • SQL (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • GitHub
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    제네릭
    rotting oranges
    운영체제
    @JsonProperty
    Reorder List
    LinkedList
    JSCode
    준영속 엔티티
    lower bounded wildcards
    트랜잭션
    Generic
    fcfs
    디자인 패턴
    runner 기법
    wildcards
    clone graph
    RR
    algorithm
    Climbing Stairs
    minimum number of arrows to burst balloons
    Oauth2
    Thread
    BFS
    @JsonNaming
    socar
    Process
    추상화 클래스
    AuthenticationSuccessHandler
    OS
    pacific atlantic water flow
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
사랑우주인
139. Word Break

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.