作者Rushia (みけねこ的鼻屎)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Mon Aug 21 18:02:48 2023
https://leetcode.com/problems/repeated-substring-pattern/description/
459. Repeated Substring Pattern
給你一個字串s,判斷s是否可以被切成多個完全相同的子字串。
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:
Input: s = "aba"
Output: false
Example 3:
Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc"
twice.
思路:
1.如果一個s可以被切成多個子字串,那麼他的:
1) 長度一定大於1
2) 子字串長度一定小於等於s長度/2
3) 子字串長度一定可以整除s長度
2.利用上面三點去切出所有長度為 1~s長度除二 的子串,並判斷全由子字串組成的新字串
是否等於s即可。
Java Code:
----------------------------------------------------
class Solution {
public boolean repeatedSubstringPattern(String s) {
if (s.length() < 2) {
return false;
}
for (int i = 1; i <= s.length() / 2; i++) {
String subString = s.substring(0, i);
if (s.length() % subString.length() != 0) {
continue;
}
StringBuilder compareString = new StringBuilder();
while (compareString.length() < s.length()) {
compareString.append(subString);
}
if (compareString.toString().equals(s)) {
return true;
}
}
return false;
}
}
----------------------------------------------------
--
https://i.imgur.com/uiFto42.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1692612170.A.807.html
推 JIWP: 大師 08/21 18:03
推 Murasakisalt: ㄉㄚ ㄘˇ 08/21 18:03
推 JerryChungYC: 大師 08/21 18:11
推 DJYOSHITAKA: 大濕 08/21 18:25