๋ฌธ์
๋ฌธ์ ํ์ด
์ ๋ ฅ๋ฐ์ S ๋ฐฐ์ด์์ ๋ ๋์ ์ ์ ์ธํ ๋ฐฐ์ด์ ์๋ก ๋ง๋ค๊ณ ์ ํ๋ฐ์ ๋ ๋์ ์ ๋ ๋ฐ๋ก temp ๋ฐฐ์ด๋ก ๋ง๋ค์ด์ T ๋ฐฐ์ด๊ณผ ๋น๊ตํ ๋ ์ฌ์ฉํ๋ค. find ํจ์๋ฅผ ์ด์ฉํด์ ์กฐ๊ฑด์ ๋ฐ๋ผ ์ฌ๊ท์ ์ผ๋ก ํ์๋ค.
find ํจ์
1. s ๋ฐฐ์ด index ๊ฐ + ๋ ๋์ ์ฌ์ฉ ํ์ == n-1์ด๋ฉด ํ์ ์๋ฃ, 1์ return
2. index๊ฐ n-2์ธ ๊ฒฝ์ฐ -> T๋ก ๋ง๋ค ์ ์๋ค. 0์ return (ex) oxo ์์ x,o๋ฅผ ๋ฝ์์ oox๋ฅผ ๋ง๋๋ ๊ฒฝ์ฐ)
3. s[index] == t[index+cnt] ์ด๋ฉด index๋ฅผ ์ฆ๊ฐ์์ผ์ ๋ค์ ๊ฐ์ ๋น๊ตํ๋ค.
4. ๋ ๋์ ์ฌ์ฉ ํ์๊ฐ 2์ธ ๊ฒฝ์ฐ; ์์์ ํด๋นํ๋ ๊ฒฝ์ฐ๊ฐ ์์๊ธฐ์ ์ ํํ ๋์ ์ ์๋ก ๋ฃ์ด ๋ณํ๋ฅผ ์ฃผ์ด์ผ ํ๋๋ฐ ๊ทธ ๋ด ์ ์์ผ๋ฏ๋ก 0 return
5. temp[cnt] == t[index+cnt] ์ด๋ฉด ์ ํํ ๋์ ์ ํด๋น ์์น์ ์ฌ์ฉ. cnt ์ฆ๊ฐ. s๋ฐฐ์ด๊ณผ ๋น๊ตํ ๊ฒ์ด ์๋๊ธฐ์ index ๊ฐ ์ ์ฆ๊ฐ ํ์ง ์๋๋ค.
์ฝ๋
import java.io.*;
import java.util.StringTokenizer;
public class Main {
static int n;
static char s[],t[],temp[];
public static int find(int index, int cnt) {
if (index+cnt==n-1) {//sํ์ ์๋ฃ+temp์ฌ์ฉ ์๋ฃ
return 1;
}
if(index==n-2) return 0;
if(s[index]==t[index+cnt]) { //๊ฐ์ผ๋ฉด ๋ค์ ์์
if(find(index+1,cnt)==1) return 1;
}
if(cnt==2)return 0; //๋ฐฐ์ด ๋ค๋ฅผ ๋ temp ๋ค ์ด ๊ฒฝ์ฐ
if(temp[cnt]==t[index+cnt]) {//์๋ง๋ ๋ถ๋ถ์ด๋ temp๋ถ๋ถ์ด๋ ๊ฐ์์ง
if(find(index,cnt+1)==1) return 1; //๊ฐ์ผ๋ฉด temp ํ๋ ์ฌ์ฉ
}
return 0;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(bf.readLine());
s=bf.readLine().toCharArray();
t=bf.readLine().toCharArray();
int a,b;
StringTokenizer st=new StringTokenizer(bf.readLine());
a=Integer.parseInt(st.nextToken());
b=Integer.parseInt(st.nextToken());
temp= new char[2];
temp[0]=s[a];
temp[1]=s[b];
int t=0;
for(int i=0;i<n;i++) {
if(i==a||i==b)continue;
s[t]=s[i];
t++;
}
int result=find(0,0);
if(result==1){
System.out.print("YES");
}
else {
System.out.print("NO");
}
}
}
๊ธฐํ
dp ๋ฌธ์ ์ธ ๊ฒ ๊ฐ์๋๋ฐ ์ด๋ป๊ฒ ํด์ผํ ์ง ๋ชฐ๋ผ์ recursiveํ๊ฒ ํ์๋ค.
ํ์ด์ฌ์ด์์ผ๋ฉด ์๊ฐ์ด๊ณผ ๋ฌ์ ๊ฒ ๊ฐ์๋ฐ ๋คํ์ด๋ ์์ง ์๋ฐ๊ฐ ์ต์ํ์ง ์์์ ์ฝ๋ ์ง๋ ๋ฐ ์ค๋๊ฑธ๋ ธ์ ใ ใ
๋ด๊ฐ ๊ณ ๋ คํ์ง ๋ชปํ๋ ์์ธ์ ์ธ ์ํฉ๋ค์ด ์์ด์ ์ฝ๋ ์ ์ถํ๋ฉด์ ๋ฐ๋ก ์ฐพ๊ณ , ์กฐ๊ฑด ์ถ๊ฐํ๋ฉด์ ์งฐ๋๋ ๊น๋ํ์ง๋ ์์ ๋๋ ์์ฝ๋ฐ
'๐ป ์๊ณ ๋ฆฌ์ฆ > PS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ/๋ฐฑ์ค] 9024 ๋ ์์ ํฉ - ํ์ด์ฌ (0) | 2021.11.01 |
---|---|
[BOJ/๋ฐฑ์ค] 20041 Escaping - ์๋ฐ,ํ์ด์ฌ (2) | 2021.10.08 |
[BOJ/๋ฐฑ์ค] 19538 ๋ฃจ๋จธ - ํ์ด์ฌ (0) | 2021.09.17 |
[BOJ/๋ฐฑ์ค] 1074 Z - ํ์ด์ฌ (0) | 2021.09.17 |
[BOJ/๋ฐฑ์ค] 14891 ํฑ๋๋ฐํด - ํ์ด์ฌ (0) | 2021.09.15 |