From b8bb7786a41a78bca103f686398fd2801e43bdbb Mon Sep 17 00:00:00 2001 From: hk27xing <244798299@qq.com> Date: Wed, 19 May 2021 16:23:04 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00459.=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E7=9A=84=E5=AD=90=E5=AD=97=E7=AC=A6=E4=B8=B2Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0459.重复的子字符串.md | 31 +++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index 5abc999a..3a5f3b17 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -149,9 +149,38 @@ public: ## 其他语言版本 - Java: +```java +class Solution { + public boolean repeatedSubstringPattern(String s) { + if (s.equals("")) return false; + + int len = s.length(); + // 原串加个空格(哨兵),使下标从1开始,这样j从0开始,也不用初始化了 + s = " " + s; + char[] chars = s.toCharArray(); + int[] next = new int[len + 1]; + + // 构造 next 数组过程,j从0开始(空格),i从2开始 + for (int i = 2, j = 0; i <= len; i++) { + // 匹配不成功,j回到前一位置 next 数组所对应的值 + while (j > 0 && chars[i] != chars[j + 1]) j = next[j]; + // 匹配成功,j往后移 + if (chars[i] == chars[j + 1]) j++; + // 更新 next 数组的值 + next[i] = j; + } + + // 最后判断是否是重复的子字符串,这里 next[len] 即代表next数组末尾的值 + if (next[len] > 0 && len % (len - next[len]) == 0) { + return true; + } + return false; + } +} +``` + Python: