import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * **/ public class Main5 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); String s = scanner.next(); int q = scanner.nextInt(); int[][] query=new int[q][2]; for (int i = 0; i < query.length; i++) { for (int j = 0; j < 2; j++) { query[i][j]= scanner.nextInt(); } } for (int[] ints : query) { String temp = s.substring(ints[0] - 1, ints[1]); List<List<String>> lists=new ArrayList<>(); List<String> list=new ArrayList<>(); backtracking(temp,lists,list); System.out.println(minSize(lists)); } } private static int minSize(List<List<String>> lists){ int min=Integer.MAX_VALUE; for (List<String> list : lists) { min= Math.min(min,list.size()); } return min; } private static void backtracking(String temp, List<List<String>> lists, List<String> list) { if (temp.length() == 0) { lists.add(new ArrayList<>(list)); return; } for (int i = 0; i < temp.length(); i++) { if (isHuiWen(temp, 0, i)) { list.add(temp.substring(0,i+1)); backtracking(temp.substring(i+1), lists, list); list.remove(list.size()-1); } } } private static boolean isHuiWen(String s,int start,int end){ while (start < end) { if (s.charAt(start) != s.charAt(end)) { return false; } start++; end--; } return true; } }
全部评论
(3) 回帖