Google Kickstart2018 Round F Problem A 555. 相同字母异序词

  1. 相同字母异序词

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;
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值