1 条题解
-
0
方法思路
- 对于每个可能的周期长度k,我们需要检查是否可以通过替换*使得整个字符串具有周期k
- 如果可以,我们需要确定周期字符串的具体内容(即前k个字符)
- 对于周期内的每个位置,如果有多个周期重复,我们需要确保所有周期中对应位置的字符可以一致
- 如果某个位置在不同周期中出现了不同的非*字符,则该周期长度无效
- 如果某个位置在所有周期中都是*,则在最终周期中保留*
- 如果某个位置在某些周期中是确定字符(0或1),在其他周期中是*,则在最终周期中使用确定字符
代码实现
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); scanner.close(); Result result = solve(s); System.out.println(result.k); System.out.println(result.period); } static class Result { int k; String period; Result(int k, String period) { this.k = k; this.period = period; } } private static Result solve(String s) { int n = s.length(); for (int k = 1; k < n; k++) { // 检查周期k是否有效 boolean valid = true; for (int i = 0; i < n - k; i++) { char c1 = s.charAt(i); char c2 = s.charAt(i + k); if (c1 != '*' && c2 != '*' && c1 != c2) { valid = false; break; } } if (!valid) continue; // 构建最优周期字符串 char[] period = new char[k]; for (int i = 0; i < k; i++) { period[i] = '*'; } for (int i = 0; i < n; i++) { int pos = i % k; char c = s.charAt(i); if (c != '*') { if (period[pos] == '*') { period[pos] = c; } else if (period[pos] != c) { valid = false; break; } } } if (valid) { return new Result(k, new String(period)); } } return new Result(n, s); } }
Python
def solve(s): n = len(s) for k in range(1, n): # 检查周期k是否有效 valid = True for i in range(n - k): if s[i] != '*' and s[i + k] != '*' and s[i] != s[i + k]: valid = False break if not valid: continue # 构建最优周期字符串 period = ['*'] * k for i in range(n): pos = i % k if s[i] != '*': if period[pos] == '*': period[pos] = s[i] elif period[pos] != s[i]: valid = False break if valid: return k, ''.join(period) # 如果没有更小的周期,则整个字符串是周期 return n, s s = input().strip() k, period = solve(s) print(k) print(period)
C++
#include <iostream> #include <string> #include <vector> using namespace std; pair<int, string> solve(const string& s) { int n = s.length(); for (int k = 1; k < n; k++) { // 检查周期k是否有效 bool valid = true; for (int i = 0; i < n - k; i++) { if (s[i] != '*' && s[i + k] != '*' && s[i] != s[i + k]) { valid = false; break; } } if (!valid) continue; // 构建最优周期字符串 vector<char> period(k, '*'); for (int i = 0; i < n; i++) { int pos = i % k; if (s[i] != '*') { if (period[pos] == '*') { period[pos] = s[i]; } else if (period[pos] != s[i]) { valid = false; break; } } } if (valid) { string periodStr(period.begin(), period.end()); return {k, periodStr}; } } return {n, s}; } int main() { string s; cin >> s; auto [k, period] = solve(s); cout << k << endl; cout << period << endl; return 0; }
- 1
信息
- ID
- 52
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者