Skip to content

Commit d5db2f4

Browse files
committed
add word break solution
1 parent 77d3ff2 commit d5db2f4

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

word-break/Tessa1217.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* 문자열 s가 주어질 때 wordDict의 단어 문자열로 s가 구성될 수 있는지 여부를 반환하세요.
3+
*/
4+
class Solution {
5+
public boolean wordBreak(String s, List<String> wordDict) {
6+
int n = s.length();
7+
boolean[] dp = new boolean[n + 1];
8+
dp[0] = true;
9+
10+
// contains 최적화를 위해 Set 선언: 시간 복잡도: O(n^2)
11+
Set<String> wordSet = new HashSet<>(wordDict);
12+
13+
for (int i = 1; i <= n; i++) {
14+
for (int j = 0; j < i; j++) {
15+
String word = s.substring(j, i);
16+
if (dp[j] && wordSet.contains(word)) {
17+
dp[i] = true;
18+
break;
19+
}
20+
}
21+
}
22+
return dp[n];
23+
}
24+
}
25+

0 commit comments

Comments
 (0)