Skip to content

Commit b91d5be

Browse files
committed
word break solution
1 parent 257c074 commit b91d5be

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

โ€Žword-break/Yn3-3xh.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
[๋ฌธ์ œํ’€์ด]
3+
- startsWith์œผ๋กœ ์žˆ์œผ๋ฉด substringํ•˜๋ฉด์„œ ๋ฐ˜๋ณตํ•ด๋ณด์ž.
4+
- ์ฃผ์–ด์ง„ list๋ฅผ map์œผ๋กœ ํ™œ์šฉ
5+
- failed
6+
s = "cars"
7+
wordDict = ["car","ca","rs"]
8+
---
9+
class Solution {
10+
public boolean wordBreak(String s, List<String> wordDict) {
11+
for (String word: wordDict) {
12+
s = s.replace(word, "");
13+
}
14+
15+
if (s.length() == 0) {
16+
return true;
17+
}
18+
return false;
19+
}
20+
}
21+
22+
- DP
23+
time: O(N^2), space: O(N)
24+
25+
[ํšŒ๊ณ ]
26+
์ฒ˜์Œ์—” ๋„ˆ๋ฌด ์‰ฝ๊ฒŒ ์ƒ๊ฐํ•ด์„œ ์•ˆ๋  ๊ฒƒ ๊ฐ™๊ธดํ–ˆ๋‹ค..
27+
DP๋กœ ํ’€๋ฉด ๋  ๊ฒƒ ๊ฐ™์€๋ฐ..
28+
ํ•ด์„ค์„ ๋ณด๋ฉด ์ดํ•ด๊ฐ€ ๋˜์ง€๋งŒ, ํ•ญ์ƒ DP ์ ‘๊ทผ์ด ์ž˜ ์•ˆ๋œ๋‹ค..
29+
*/
30+
class Solution {
31+
public boolean wordBreak(String s, List<String> wordDict) {
32+
// "applepenapple", ["apple","pen"]
33+
int sLen = s.length();
34+
boolean[] dp = new boolean[sLen + 1];
35+
dp[0] = true;
36+
37+
int maxLen = 0;
38+
for (String word: wordDict) {
39+
maxLen = Math.max(maxLen, word.length());
40+
} // 5
41+
42+
for (int i = 1; i <= sLen; i++) { // 1 ~ 13
43+
// applepenapple > apple > 5
44+
for (int j = i - 1; j >= 0; j--) {
45+
// applepenapple > apple > index:4 > 0
46+
if (dp[j] && wordDict.contains(s.substring(j, i))) {
47+
dp[i] = true;
48+
break;
49+
}
50+
}
51+
}
52+
return dp[sLen];
53+
}
54+
}
55+

0 commit comments

Comments
ย (0)