leetcode 459. 重复的子字符串(Java版)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 459. 重复的子字符串(Java版)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode-cn.com/problems/repeated-substring-pattern/
思路
暴力解法 + 剪枝優化
經過嘗試,如果直接使用暴力解法會超時,于是想到了一種剪枝的方式:
假設子串的長度為 step,原串的長度為 length。從直觀上來看,原串的長度必然為子串長度的倍數,即,只有當 length%step==0 時,才有可能成為正確的子串。根據這個結論,進行剪枝優化。
代碼
評論區說,簡單題就是暴力解能通過的題。本文用的暴力解,優化之后才勉強 AC。
class Solution {public static boolean repeatedSubstringPattern(String s) {char[] charArray = s.toCharArray();int step = 0;while (step < s.length() / 2) {// 遍歷每個步長step++;// 剪枝優化while (charArray.length % step != 0) {step++;}// 當前步長是否能匹配int i, j;for (i = 0, j = 0; i < charArray.length; i++, j++) {j %= step;if (charArray[i] != charArray[j]) break;}if (i == charArray.length && charArray.length % step == 0 && step < s.length()) {return true;}}return false;} }總結
以上是生活随笔為你收集整理的leetcode 459. 重复的子字符串(Java版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 455. 分发饼干(J
- 下一篇: leetcode 461. 汉明距离(J