Skip to content

Commit 07f74d0

Browse files
committed
sovle #139
1 parent 8d6654f commit 07f74d0

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,4 @@ mod n0134_gas_station;
135135
mod n0135_candy;
136136
mod n0136_single_number;
137137
mod n0137_single_number_ii;
138+
mod n0139_word_break;

src/n0139_word_break.rs

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
* [139] Word Break
3+
*
4+
* Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
5+
*
6+
* Note:
7+
*
8+
*
9+
* The same word in the dictionary may be reused multiple times in the segmentation.
10+
* You may assume the dictionary does not contain duplicate words.
11+
*
12+
*
13+
* Example 1:
14+
*
15+
*
16+
* Input: s = "leetcode", wordDict = ["leet", "code"]
17+
* Output: true
18+
* Explanation: Return true because "leetcode" can be segmented as "leet code".
19+
*
20+
*
21+
* Example 2:
22+
*
23+
*
24+
* Input: s = "applepenapple", wordDict = ["apple", "pen"]
25+
* Output: true
26+
* Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
27+
* Note that you are allowed to reuse a dictionary word.
28+
*
29+
*
30+
* Example 3:
31+
*
32+
*
33+
* Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
34+
* Output: false
35+
*
36+
*
37+
*/
38+
pub struct Solution {}
39+
40+
/*
41+
记 f[n] 表示从 0 开始长度为 n 的 substring 是否可以被组成,那么:
42+
43+
f[n] = f[k] && (s[k..n] in dict)
44+
f[0] = true
45+
46+
DP 向上递推即可
47+
48+
BFS 也是可以的
49+
*/
50+
51+
// submission codes start here
52+
53+
use std::collections::HashSet;
54+
impl Solution {
55+
pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
56+
let word_dict = word_dict.into_iter().collect::<HashSet<_>>();
57+
let mut dp = vec![false; s.len()+1];
58+
dp[0] = true;
59+
for i in 1..s.len()+1 {
60+
for j in 0..s.len() {
61+
if dp[j] && word_dict.contains(&s[j..i]) {
62+
dp[i] = true;
63+
}
64+
}
65+
}
66+
dp[s.len()]
67+
}
68+
}
69+
70+
// submission codes end
71+
72+
#[cfg(test)]
73+
mod tests {
74+
use super::*;
75+
76+
#[test]
77+
fn test_139() {
78+
assert_eq!(Solution::word_break("leetcode".to_owned(), vec_string!["leet", "code"]), true);
79+
assert_eq!(Solution::word_break("catsandog".to_owned(), vec_string!["cats", "dog", "sand", "and", "cat"]), false);
80+
}
81+
}

0 commit comments

Comments
 (0)