From 0dad9a5f7cd13b68b9a727983490bea2a5eaa992 Mon Sep 17 00:00:00 2001 From: zhicheng lee <904688436@qq.com> Date: Tue, 13 Sep 2022 22:21:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200139.=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=E6=8B=86=E5=88=86.md=20Java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用Set容器加速两层for循环中的查询函数,原代码在List列表中查询,本质上为三层循环,使用Set容器后为两层循环 --- problems/0139.单词拆分.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index 7ff13f72..5b38a7a5 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -234,11 +234,13 @@ Java: ```java class Solution { public boolean wordBreak(String s, List wordDict) { + HashSet set = new HashSet<>(wordDict); boolean[] valid = new boolean[s.length() + 1]; valid[0] = true; + for (int i = 1; i <= s.length(); i++) { - for (int j = 0; j < i; j++) { - if (wordDict.contains(s.substring(j,i)) && valid[j]) { + for (int j = 0; j < i && !valid[i]; j++) { + if (set.contains(s.substring(j, i)) && valid[j]) { valid[i] = true; } }