Algorithm
[백준 12871] 무한문자열 (C++, Java)
WantAirpod
2020. 9. 3. 21:32
반응형
12871번: 무한 문자열
첫째 줄에 s, 둘째 줄에 t가 주어진다. 두 문자열 s와 t의 길이는 50보다 작거나 같은 자연수이고, 알파벳 소문자로만 이루어져 있다.
www.acmicpc.net
해결방법
- ab <-> abab 일 경우
- 포인터를 있다고 가정하여 문자열이 끝나면 다시 0으로 옮겨 주는 방법
코드
C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string s, t;
int che = 0;
void solve() {
if (s.size() > t.size()) swap(s, t); // swap 개꿀...
int a = 0; int b = 0;
bool flag = false;
int ct = 0;
while (ct <= 500) {
if (s[a] != t[b]) {
che = 0;
flag = true;
break;
}
a++;
b++;
if (a == s.size()) a = 0;
if (b == t.size()) b = 0;
ct++;
}
if (!flag) che = 1;
}
int main() {
cin >> s >> t;
solve();
cout << che << endl;
return 0;
}
Java
import java.io.*;
public class Main {
static int che =0;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();//ab
String t = br.readLine();//abab
if(s.length() > t.length())
{
String tmp;
tmp = s;
s = t;
t = tmp;
}
int a=0;
int b=0;
boolean flag = false;
int ct = 0;
while(ct<=500)
{
if(s.charAt(a) != t.charAt(b))
{
che = 0;
flag = true;
break;
}
a++;
b++;
if(a==s.length())
a=0;
if(b==t.length())
b=0;
ct++;
}
if(!flag) che=1;
System.out.println(che);
}
}
반응형