【題目敘述】https://zerojudge.tw/ShowProblem?problemid=e537
【解題想法】
- 將另一個長度為k的字串的一個或多個重複連接起來
- k 為原字串長度的因數
- 由 1 開始枚舉可能的 k
#include <iostream>
#include <set>
using namespace std;
int main() {
int T;
string s;
cin >> T;
getline(cin, s); //"\n"
while (T--){
getline(cin, s); //空白行
getline(cin, s);
int len = s.size();
int period = 1;
set <string> st;
while (period <= len) {
st.clear();
if (len % period == 0) {
for (int i = 0; i < len; i+=period){
st.insert(s.substr(i, period));
}
}
if (st.size() == 1) break;
period++;
}
cout << period << "\n";
}
return 0;
}
Python code (credit: Amy Chou)
T = int(input())
for _ in range(T):
s = input() #第一行為一個空白行
s = input()
L = len(s)
period = 1
while period <= L:
st = set()
if len(s) % period == 0:
for i in range(0, L, period):
st.add(s[i:i+period])
if len(st) == 1:
break
else:
period += 1
print(period)