- 相同字母异序词
https://www.acwing.com/problem/content/description/557/
Ayla有两个字符串A和B,每个字符串长度为L,每个字符串均由大写英文字母组成。
她想知道有多少个不同的A的子串可以在B中找到一个子串是它的“相同字母异序词”。
如果两个字符串的长度相同,组成字符串的字母和每个字母出现的次数也都相同,则这两个字符串为“相同字母异序词”。
例如,AABC和ABAC。
总结:
1、两重for循环 遍历子串
2、对于每个子串 因为是字母 所以统计次数除了hash表 还有arr[26]
3、数组可以利用P进制(131、13331)映射为hash值,存到hash表
4、两个子串相似时,arr相同,hash相同,倒过来同样成立,从而知道B中有没有A对应的相似串。
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int cases = 1; cases <= t; cases++) {
int n = sc.nextInt();// 串长度
sc.nextLine();// !!! 接收int后接收字符串 必须nextLine一次
String A = sc.nextLine();// A串
String B = sc.nextLine();// B串
Map<Integer, Integer> map = new HashMap<>();
// 两重for循环遍历子串
for(int i = 0; i < n; i++) {
for(int j = i; j < n; j++) {
int[] arr = new int[26];
for(int k = i; k <= j; k++)
arr[B.charAt(k) - 'A']++;
map.put(get_hash(arr), 1);
}
}
int res = 0;
for(int i = 0; i < n; i++) {
for(int j = i; j < n; j++) {
int[] arr = new int[26];
for(int k = i; k <= j; k++)
arr[A.charAt(k) - 'A']++;
if(map.containsKey(get_hash(arr))) res++;
}
}
System.out.println("Cases #" + cases + ": " + res);
}
}
public static int get_hash(int[] s) {
int P = 131;// P进制 131或13331 因为不容易哈希冲突
int res = 0;
for(int i = 0; i < s.length; i++)
res = res * P + s[i];
return res;
}
}