美团9.3笔试字母树Java
public class CharacterTree{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] num = new int[n - 1];
int[] ans = new int[n];
ArrayList<Integer>[] nm = new ArrayList[n];
for(int i = 0; i < n ;i++){
nm[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i++) {
num[i] = scanner.nextInt();
nm[num[i] - 1].add(Integer.valueOf(i + 1));
}
scanner.nextLine();
String string = scanner.nextLine();
for (int i = 0; i < n; i++) {
Queue<Integer> queue = new LinkedList<>();
queue.add(i);
Set<Character> set = new HashSet<>();
int count = 0;
while (!queue.isEmpty()){
int top = queue.peek();
queue.poll();
if(!set.contains(string.charAt(top))){
count++;
set.add(string.charAt(top));
}
for (Integer j : nm[top]){
queue.add(j);
}
}
ans[i] = count;
}
for (int i = 0; i < n; i++) {
System.out.println(ans[i]);
}
}
}
#美团笔试#
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] num = new int[n - 1];
int[] ans = new int[n];
ArrayList<Integer>[] nm = new ArrayList[n];
for(int i = 0; i < n ;i++){
nm[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i++) {
num[i] = scanner.nextInt();
nm[num[i] - 1].add(Integer.valueOf(i + 1));
}
scanner.nextLine();
String string = scanner.nextLine();
for (int i = 0; i < n; i++) {
Queue<Integer> queue = new LinkedList<>();
queue.add(i);
Set<Character> set = new HashSet<>();
int count = 0;
while (!queue.isEmpty()){
int top = queue.peek();
queue.poll();
if(!set.contains(string.charAt(top))){
count++;
set.add(string.charAt(top));
}
for (Integer j : nm[top]){
queue.add(j);
}
}
ans[i] = count;
}
for (int i = 0; i < n; i++) {
System.out.println(ans[i]);
}
}
}
#美团笔试#