Guest User

Untitled

a guest
Feb 10th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.Arrays;
  5.  
  6. import static java.lang.Integer.min;
  7.  
  8. /**
  9.  * Created by bugkiller on 10/02/18.
  10.  */
  11.  
  12. class Aibohphobia {
  13.     static int[][] dp = new int[6101][6101];
  14.  
  15.     public static void main(String[] args) throws IOException {
  16.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  17.         int t = Integer.parseInt(br.readLine());
  18.         while (t-- > 0) {
  19.             char[] s = br.readLine().toCharArray();
  20.             System.out.println(solve(s, s.length));
  21.         }
  22.     }
  23.  
  24.     private static int solve(char[] s, int n) {
  25.         for (int i = 0; i < n; i++) {
  26.             Arrays.fill(dp[i], 0, n, -1);
  27.         }
  28.         return minCost(s, 0, n - 1);
  29.     }
  30.  
  31.     private static int minCost(char[] s, int start, int end) {
  32.         if (start >= end)
  33.             return 0;
  34.  
  35.         if (dp[start][end]!=-1)
  36.             return dp[start][end];
  37.  
  38.         if (s[start]==s[end])
  39.             dp[start][end] = minCost(s, start + 1, end - 1);
  40.  
  41.         else
  42.             dp[start][end] = 1 + min(minCost(s, start, end - 1), minCost(s, start + 1, end));
  43.  
  44.         return dp[start][end];
  45.     }
  46.  
  47. }
Add Comment
Please, Sign In to add comment