Skip to content

Commit e3810cf

Browse files
authored
[20250713] BOJ / G1 / 팰린드롬 분할 / 이강현
1 parent c6368ca commit e3810cf

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
public class Main{
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
static StringTokenizer st;
9+
static boolean[][] dp;
10+
static int[] dp2;
11+
12+
public static void main(String[] args) throws Exception{
13+
String str = br.readLine();
14+
int len = str.length();
15+
dp = new boolean[len][len];
16+
17+
for (int i = 0; i < len; i++) { // 한 자리
18+
dp[i][i] = true;
19+
}
20+
for (int i = 0; i < len-1; i++) { // 두 자리
21+
if(str.charAt(i) == str.charAt(i+1)) {
22+
dp[i][i+1] = true;
23+
}
24+
}
25+
26+
for (int i = 2; i < len; i++) { // 그외
27+
for (int j = 0; j+i < len; j++) {
28+
if(str.charAt(j) == str.charAt(i+j)){
29+
dp[j][i+j] = dp[j+1][i+j-1];
30+
}else{
31+
dp[j][i+j] = false;
32+
}
33+
}
34+
}
35+
36+
dp2 = new int[len+1]; //0부터 시작해서 i까지의 문자까지 보았을 때 팰린드롬으로 분할하는 최소 개수
37+
Arrays.fill(dp2, Integer.MAX_VALUE);
38+
dp2[0] = 0;
39+
40+
for (int i = 1; i <= len; i++) { //모든 길이에 대해서
41+
for (int j = 0; j < i; j++) { //첫번째 문자부터 보기
42+
if(dp[j][i-1]){ //j지점에서 문자열 끝까지 팰린드롬이면
43+
dp2[i] = Math.min(dp2[i], dp2[j] + 1); //j지점까지의 분할 개수와 j지점 이후는 팰린드롬이므로 1을 더해주기
44+
}
45+
}
46+
}
47+
48+
bw.write(dp2[len] + "");
49+
bw.close();
50+
}
51+
}
52+
```

0 commit comments

Comments
 (0)