Skip to content

Commit 8907e95

Browse files
update post
1 parent 3cdce51 commit 8907e95

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

_posts/2024-02-28-leetcode-139.md

+33-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
---
22
layout: post
3-
title: (Leetcode) 139 - Word Break
3+
title: (Leetcode) 139 - Word Break 풀이
44
categories: [스터디-알고리즘]
5-
tags: [파이썬, 알고리즘, python, algorithm, Leetcode, DP, word]
5+
tags: [파이썬, 알고리즘, python, algorithm, Leetcode, DP, word, java, 자바]
66
date: 2024-02-28 12:30:00 +0900
77
---
88

@@ -65,13 +65,43 @@ dp[7]의 경우 뒤를 확인해보면 sand 라는 단어를 가지고 있다.
6565
하지만 이런식으로 좀 더 진행해보면 최종적으로 마지막은 False가 나온다.
6666

6767
### 시간복잡도
68+
6869
- 이중 반복문 사용
6970
- 바깥쪽 반복문 : s의 길이 만큼 반복 (O(n))
7071
- 안쪽 반복문 : wordDict 리스트의 length 만큼 반복 (O(m))
7172

7273
`O(n * m)` 의 시간 복잡도를 가짐
7374

7475
### 공간복잡도
76+
7577
s의 길이만큼 dp 리스트를 생성함
7678

77-
`O(n)` 의 공간 복잡도를 가짐
79+
`O(n)` 의 공간 복잡도를 가짐
80+
81+
## 자바로 다시 풀어보기 (240709)
82+
83+
```java
84+
class Solution {
85+
public boolean wordBreak(String s, List<String> wordDict) {
86+
boolean[] dp = new boolean[s.length() + 1];
87+
dp[0] = true;
88+
89+
for (int i = 1; i <= s.length(); i++) {
90+
for (String word : wordDict) {
91+
if (i >= word.length()) {
92+
int start = i - word.length();
93+
if (dp[start] && s.startsWith(word, start)) {
94+
dp[i] = true;
95+
}
96+
}
97+
}
98+
}
99+
100+
return dp[s.length()];
101+
}
102+
}
103+
```
104+
105+
### TC, SC
106+
107+
s의 길이를 n 이라 하고, wordDict의 크기를 m 이라고 할 때, 시간복잡도는 `O(n * m)` 공간복잡도는 `O(n)` 이다.

0 commit comments

Comments
 (0)