Algorithm/BaeKJoon
[JS][백준]12871_무한 문자열
JaeKwan
2021. 9. 14. 21:59
문제 번호
12871번: 무한 문자열
첫째 줄에 s, 둘째 줄에 t가 주어진다. 두 문자열 s와 t의 길이는 50보다 작거나 같은 자연수이고, 알파벳 소문자로만 이루어져 있다.
www.acmicpc.net
알고리즘 분류
수학, 구현, 문자열
문제 풀이
검색해보면 LCM을 이용하는 방법들이 주로 나온다.
그래서 나는 다른분께 질문해서 들은 내용으로 문제를 풀어보려고한다. 최대공배수를 구한다음 주어진 문자열들을 최대공배수 만큼 자른다. 그 후 잘린 문자열들을 비교해서 모두 같은내용이라면 '1' 이다.
const fs = require('fs');
const input = fs.readFileSync('무한 문자열/input.txt').toString().trim().split('\n');
let s = input.shift().trim();
let t = input.shift().trim();
function GCD(a,b){
while(b!=0){
let n = a%b;
a=b;
b=n;
}
return a;
}
let gcd = GCD(s.length,t.length);
let temp = [];
for(let i=0; i<s.length; i+=gcd){
temp.push(s.substring(i, i+gcd));
}
for(let i=0; i<t.length; i+=gcd){
temp.push(t.substr(i,i+gcd));
}
for(let i=0; i<temp.length; i++){
if(temp[i] !== temp[0]){
console.log(0);
return 0;
}
}
console.log(1);
특이사항