Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4c6a31f

Browse files
MEDIUM/src/medium/WordBreak.java
1 parent3f39570 commit4c6a31f

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

‎MEDIUM/src/medium/WordBreak.java

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ public class WordBreak {
66

77
//Jiuzhang gives a very good illustration for this problem!
88

9-
publicbooleanwordBreak(Strings,Set<String>wordDict) {
9+
publicbooleanwordBreak_2ms(Strings,Set<String>wordDict) {
1010
intmaxLen =Integer.MIN_VALUE;
1111
for(Stringword :wordDict){
1212
maxLen = (word.length() >maxLen) ?word.length() :maxLen;
@@ -16,10 +16,10 @@ public boolean wordBreak(String s, Set<String> wordDict) {
1616
boolean[]dp =newboolean[n+1];
1717
dp[0] =true;
1818
for(inti =1;i <=n;i++){
19-
for(intj =1;j <=i &&j <=maxLen;j++){
20-
if(!dp[i-j])continue;
19+
for(intlastWordLength =1;lastWordLength <=i &&lastWordLength <=maxLen;lastWordLength++){
20+
if(!dp[i-lastWordLength])continue;
2121

22-
Stringsub =s.substring(i-j,i);
22+
Stringsub =s.substring(i-lastWordLength,i);
2323
if(wordDict.contains(sub)){
2424
dp[i] =true;
2525
break;
@@ -29,5 +29,29 @@ public boolean wordBreak(String s, Set<String> wordDict) {
2929

3030
returndp[n];
3131
}
32+
33+
34+
//this is much slower, although AC'ed on Leetcode, TLE on Lintcode.
35+
//This is because in the inner for loop, this method is looping from left to right which is unnecessary, we only need to find the
36+
//right-most true element, then check that substring. That's why we could write wordBreak_2ms() above.
37+
publicbooleanwordBreak_14ms(Strings,Set<String>wordDict) {
38+
intn =s.length();
39+
boolean[]dp =newboolean[n+1];
40+
dp[0] =true;
41+
for(inti =1;i <=n;i++){
42+
for(intj =0;j <i;j++){
43+
if(!dp[j])continue;
44+
45+
Stringsub =s.substring(j,i);
46+
if(wordDict.contains(sub)){
47+
dp[i] =true;
48+
break;
49+
}
50+
}
51+
}
52+
53+
returndp[n];
54+
}
55+
3256

3357
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp