Skip to content

Commit b086f0d

Browse files
committed
[Create] LeetCode_139 단어블록
1 parent cd87626 commit b086f0d

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

WordBreak.java

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// LeetCode_139
2+
// 2021.04.14
3+
// String, List, Dynamic Programming
4+
// Medium
5+
6+
import java.util.*;
7+
8+
public class WordBreak {
9+
public static void main(String[] args) {
10+
List<String> list = new ArrayList<>();
11+
list.add("car");
12+
list.add("ca");
13+
list.add("rs");
14+
System.out.println(new WordBreak().wordBreak("cars", list));
15+
}
16+
public boolean wordBreak(String s, List<String> wordDict) {
17+
StringBuffer str = new StringBuffer(s);
18+
19+
// list 길이 오름차순 정렬
20+
Comparator<String> c = new Comparator<String>() {
21+
@Override
22+
public int compare(String s1, String s2) {
23+
return Integer.compare(s1.length(), s2.length());
24+
}
25+
};
26+
Collections.sort(wordDict, c);
27+
for (int i = 0; i < wordDict.size(); i++) {
28+
String word = wordDict.get(i);
29+
if (s.contains(word)) {
30+
while (true) {
31+
if (s.indexOf(word) == -1)
32+
break;
33+
str.replace(s.indexOf(word), s.indexOf(word) + word.length(), "");
34+
s = str.toString();
35+
}
36+
}
37+
}
38+
if (str.length() != 0)
39+
return false;
40+
return true;
41+
}
42+
}
43+
44+
/* USE_DP_출처: LeetCode
45+
class Solution {
46+
public boolean wordBreak(String s, List<String> wordDict) {
47+
int n = s.length();
48+
boolean[] dp = new boolean[n + 1];
49+
dp[0] = true;
50+
51+
for (int i = 1; i <= n; i++) {
52+
for (int j = 0; j < i; j++) {
53+
if (dp[j] && wordDict.contains(s.substring(j, i))) {
54+
dp[i] = true;
55+
break;
56+
}
57+
}
58+
}
59+
60+
return dp[n];
61+
62+
}
63+
}
64+
*/

0 commit comments

Comments
 (0)