import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str1 string字符串 * @param str2 string字符串 * @return string字符串 */ public String gcdOfStrings (String str1, String str2) { // write code here int len1 = str1.length(); int len2 = str2.length(); int gcd = GCD(len1, len2); // 求str1和str2长度的最大公约数 String candidate = str1.substring(0, gcd); // 取str1的前gcd个字符作为可能的公约串 // 检查str1是否由candidate重复若干次构成 for (int i = 0; i < len1; i += gcd) { if (!str1.substring(i, i + gcd).equals(candidate)) { return ""; } } // 检查str2是否由candidate重复若干次构成 for (int i = 0; i < len2; i += gcd) { if (!str2.substring(i, i + gcd).equals(candidate)) { return ""; } } return candidate; } private int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); } }
编程语言是 Java。
该题考察的知识点包括:
- 字符串的基本操作,如长度、子串提取、相等判断。
- 循环控制
代码解释:
- 在 gcdOfStrings 方法中,通过计算两个字符串的长度的最大公约数来找到可能的公约串的长度。
- 使用 substring 方法从 str1 中提取长度为 gcd 的子串作为可能的公约串 candidate。
- 通过循环遍历字符串 str1,检查每个以 gcd 为长度的子串是否与 candidate 相等。如果不相等,说明 candidate 不能生成该子串,返回空字符串。
- 类似地,通过循环遍历字符串 str2,检查每个以 gcd 为长度的子串是否与 candidate 相等。如果不相等,说明 candidate 不能生成该子串,返回空字符串。
- 如果在上述两个循环中,所有子串都与 candidate 相等,说明 candidate 可以作为满足条件的子串。
- 返回 candidate,即满足条件的最长子串。