@@ -59,4 +59,74 @@ public boolean wordBreak(String s, List<String> wordDict) {
59
59
}
60
60
return dp [n ];
61
61
}
62
+ }
63
+
64
+
65
+ /*
66
+ 广度优先:
67
+ 1、memo[i]表示前i个字符是否能由单词拼出
68
+ 2、队列queue存放的是dp[i]的索引i,前i个字符能由单词拼出,再继续判断后面的字符
69
+ 3、从队列弹出一个起始索引,遍历单词数组,根据单词扩增子串长度,判断子串长度是否合法、dp是否标记过,是否为s的子串、长度是否达到s的长度,
70
+ 满足条件则返回true,否则为有效子串就加入队列继续判断,并标记该子串位置能由单词拼出
71
+ 4、遍历结束都不满足则返回false
72
+ */
73
+ class Solution {
74
+ public boolean wordBreak (String s , List <String > wordDict ) {
75
+ int n = s .length ();
76
+ boolean [] memo = new boolean [n + 1 ];
77
+ Queue <Integer > queue = new LinkedList <>();
78
+ queue .add (0 );
79
+ while (!queue .isEmpty ()) {
80
+ int size = queue .size ();
81
+ while (size > 0 ) {
82
+ int start = queue .poll ();
83
+ for (String word : wordDict ) {
84
+ int nextStart = start + word .length ();
85
+ if (nextStart > n || memo [nextStart ]) {
86
+ continue ;
87
+ }
88
+ if (s .startsWith (word , start )) {
89
+ if (nextStart == n ) {
90
+ return true ;
91
+ }
92
+ memo [nextStart ] = true ;
93
+ queue .add (nextStart );
94
+ }
95
+ }
96
+ size --;
97
+ }
98
+ }
99
+ return false ;
100
+ }
101
+ }
102
+
103
+
104
+ /*
105
+ 深度优先:
106
+ 1、memo[i]表示前i个字符是否能由单词拼出。被标记为true表示子串能由单词拼出,但是最终不能拼出s,因为递归是一次性判断是否成功,所以该标记用于避免重复处理
107
+ 2、dfs(start) 输入参数表示前start个字符能由单词拼出,输出 前start个字符分别拼接单词数组的单词后的子串,是否为s的子串
108
+ 3、终止条件:子串有效且达到s的长度时返回true,拼接单词的子串都无效时返回false
109
+ 4、调用递归函数:子串有效但未达到s的长度,递归判断子串继续拼接单词后,是否有效且达到s的长度
110
+ */
111
+ class Solution {
112
+ public boolean wordBreak (String s , List <String > wordDict ) {
113
+ boolean [] memo = new boolean [s .length () + 1 ];
114
+ return dfs (s , wordDict , 0 , memo );
115
+ }
116
+
117
+ private boolean dfs (String s , List <String > wordDict , int start , boolean [] memo ) {
118
+ for (String word : wordDict ) {
119
+ int nextStart = start + word .length ();
120
+ if (nextStart > s .length () || memo [nextStart ]) {
121
+ continue ;
122
+ }
123
+ if (s .startsWith (word , start )) {
124
+ if (nextStart == s .length () || dfs (s , wordDict , nextStart , memo )) {
125
+ return true ;
126
+ }
127
+ memo [nextStart ] = true ;
128
+ }
129
+ }
130
+ return false ;
131
+ }
62
132
}
0 commit comments