【编程题】 字符串的最大公因子(Shopee笔试题)(java实现)
题目来源
Shopee笔试题
leetcode第1071题
https://www.sogou.com/link?url=hedJjaC291P5ZWRF64WnQ0qmF04fhX0Fd8lakktjXrM3XRC-P_LIvh5hwILBh4-tYSnziuVXEiu7BMCmiw8l80uocce-FURO
题目描述
对于字符串 S 和 T,只有在 S = T + … + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。
返回字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。
示例 1:
输入:str1 = “ABCABC”, str2 = “ABC”
输出:“ABC”
示例 2:
输入:str1 = “ABABAB”, str2 = “ABAB”
输出:“AB”
示例 3:
输入:str1 = “LEET”, str2 = “CODE”
输出:""
提示:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
题目解答
import java.util.List;
import java.util.Scanner;
public class Main2{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String s2=sc.next();
System.out.println(maxcon(s1,s2));
}
static String maxcon(String s1,String s2){
if(s1.length()<s2.length()){
String tem=s1;
s1=s2;
s2=tem;
}
if(!s1.contains(s2))
return "";
int l1=s1.length();
int l2=s2.length();
int index=l2;
while (index>=1){
if(l1%index==0&&l2%index==0) {
String tem = s2.substring(0, index);
StringBuilder sb1 = new StringBuilder(tem);
while (sb1.length() != l1) {
sb1.append(tem);
}
StringBuilder sb2 = new StringBuilder(tem);
while (sb2.length() != l2) {
sb2.append(tem);
}
if (new String(sb1).equals(s1) && new String(sb2).equals(s2))
return tem;
}
index--;
}
return "";
}
}