Home BOJ. Palindrome Devision (1509)
Post
Cancel

BOJ. Palindrome Devision (1509)

[Link] https://www.acmicpc.net/problem/1509


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringBuilder sb = new StringBuilder();
	static int INF = 987654321;
	static int pal[][];
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();
		int len = str.length();
		int[][] dp = new int[len][len];
		pal = new int[len][len];
		for(int[] ar: dp) Arrays.fill(ar, INF);
		for(int[] ar: pal) Arrays.fill(ar, -1);

		int ans = solve(dp, str, 0, len - 1);
		print(ans);
	}

	static int solve(int[][] dp, String str, int l, int r) {
		if(dp[l][r] != INF) return dp[l][r];
		if(isPalindrome(str, l, r)) return dp[l][r] =  1;
		int min = INF;
		for(int idx = l + 1; idx <= r; idx++) {
			if(isPalindrome(str, idx, r)) {
				min = Math.min(min, solve(dp, str, l, idx - 1));
			}
		}

		return dp[l][r] = min + 1;
	}

	static boolean isPalindrome(String s, int l , int r) {
		if(pal[l][r] != -1) return pal[l][r] ==  1 ? true : false;
		int origL = l, origR = r;
		while(l < r) {
			if(s.charAt(l++) != s.charAt(r--)) {
				pal[origL][origR] = 0;
				return false;
			}
		}
		pal[origL][origR] = 1;
		return true;
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static long tol(String s) { return Long.parseLong(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.