33class Solution {
44 public boolean wordBreak (String s , List <String > wordDict ) {
55 int n = s .length ();
6- boolean [] dp = new boolean [n + 1 ];
6+ boolean [] dp = new boolean [n + 1 ]; // 빈 문자열을 대비해서 +1 길이로 설정
77 dp [0 ] = true ; // 빈 문자열은 항상 가능
88
99 for (int i = 0 ; i < n ; i ++) {
@@ -17,4 +17,52 @@ public boolean wordBreak(String s, List<String> wordDict) {
1717 }
1818 return dp [n ];
1919 }
20+
21+ public boolean wordBreak2 (String s , List <String > wordDict ) {
22+ int n = s .length ();
23+ // List를 HashSet 객체 생성시 인자로 넣어 초기화가 가능합니다.
24+ // set은 List에서의 단어 탐색을 O(1) 성능으로 최적화하기 위해서 필요합니다.
25+ Set <String > wordSet = new HashSet <>(wordDict );
26+
27+ // 빈 문자열일 경우를 대비해서 +1을 길이로 설정합니다.
28+ boolean [] dp = new boolean [n + 1 ];
29+ // 빈 문자열을 항상 true이므로 0번째 dp[]에 true를 설정합니다.
30+ dp [0 ] = true ;
31+
32+ // 앞서 빈문자열을 셋팅했으니 i는 1부터 n까지 반복합니다.
33+ // j는 0부터 i보다 작을때까지 반복합니다.
34+ /**
35+ * j=0: s.substring(0, 1) = "l" | dp[0]=true | "l" in dict=false
36+ * -----
37+ * j=0: s.substring(0, 2) = "le" | dp[0]=true | "le" in dict=false
38+ * j=1: s.substring(1, 2) = "e" | dp[1]=false | "e" in dict=false
39+ * -----
40+ * j=0: s.substring(0, 3) = "lee" | dp[0]=true | "lee" in dict=false
41+ * j=1: s.substring(1, 3) = "ee" | dp[1]=false | "ee" in dict=false
42+ * j=2: s.substring(2, 3) = "e" | dp[2]=false | "e" in dict=false
43+ * -----
44+ * j=0: s.substring(0, 4) = "leet" | dp[0]=true | "leet" in dict=true → dp[4] = true!
45+ * -----
46+ * j=0: s.substring(0, 5) = "leetc" | dp[0]=true | "leetc" in dict=false
47+ * j=1: s.substring(1, 5) = "eetc" | dp[1]=false | "eetc" in dict=false
48+ * j=2: s.substring(2, 5) = "etc" | dp[2]=false | "etc" in dict=false
49+ * j=3: s.substring(3, 5) = "tc" | dp[3]=false | "tc" in dict=false
50+ * j=4: s.substring(4, 5) = "c" | dp[4]=true | "c" in dict=false
51+ * -----
52+ * j=0: s.substring(0, 8) = "leetcode" | dp[0]=true | "leetcode" in dict=false
53+ * j=1: s.substring(1, 8) = "eetcode" | dp[1]=false | "eetcode" in dict=false
54+ * j=2: s.substring(2, 8) = "etcode" | dp[2]=false | "etcode" in dict=false
55+ * j=3: s.substring(3, 8) = "tcode" | dp[3]=false | "tcode" in dict=false
56+ * j=4: s.substring(4, 8) = "code" | dp[4]=true | "code" in dict=true → dp[8] = true!
57+ */
58+ for (int i = 1 ; i <= n ; i ++) {
59+ for (int j = 0 ; j < i ; j ++) {
60+ if (dp [j ] && wordSet .contains (s .substring (j , i ))) {
61+ dp [i ] = true ;
62+ break ;
63+ }
64+ }
65+ }
66+ return dp [n ];
67+ }
2068}
0 commit comments