标题:密文搜索
福尔摩斯从X星收到一份资料,全部是小写字母组成。
他的助手提供了另一份资料:许多长度为8的密码列表。
福尔摩斯发现,这些密码是被打乱后隐藏在先前那份资料中的。
请你编写一个程序,从第一份资料中搜索可能隐藏密码的位置。要考虑密码的所有排列可能性。
数据格式:
输入第一行:一个字符串s,全部由小写字母组成,长度小于1024*1024
紧接着一行是一个整数n,表示以下有n行密码,1<=n<=1000
紧接着是n行字符串,都是小写字母组成,长度都为8
要求输出:
一个整数, 表示每行密码的所有排列在s中匹配次数的总和。
例如:
用户输入:
aaaabbbbaabbcccc
2
aaaabbbb
abcabccc
则程序应该输出:
4
这是因为:第一个密码匹配了3次,第二个密码匹配了1次,一共4次。
资源约定:
峰值内存消耗(含虚拟机) < 512M
CPU消耗 < 5000ms
这个题比较有意思,之前被题目设计的全套给坑了,以给出的密码进行全排列来匹配原字符串,这样做就相当繁琐了。
反过来想,其实很简单的:
/**
*
*/
package 决赛Java大学C组2015;
import java.util.Arrays;
import java.util.Scanner;
/**
* @作者: gx_143
* @创建时间: 2017-4-28下午09:17:41
*/
public class T5改 {
static long ans=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int n=sc.nextInt();
while(n>=0){
n--;
String s=sc.nextLine();
count(str,sort(s));
}
System.out.println(ans);
}
private static void count(String str, String sort) {
for (int i = 0; i <= str.length()-8; i++) {
String sb=str.substring(i,i+8);
sb=sort(sb);
if(sb.equals(sort))
ans++;
}
}
private static String sort(String s) {
char[] ch=s.toCharArray();
Arrays.sort(ch);
String re=new String(ch);
return re;
}
}