给字母编码后,用NC当进制进行hash,或者直接java水过
/* author:jxy lang:C/C++ university:China,Xidian University **If you need to reprint,please indicate the source** */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #define INF 1E9 using namespace std; int N,NC; char org[1000000]; int hash[10000000]; int v[200]; int find() { int i=0,j=0,now=0,hh,ans=0,len=strlen(org); for(i=0,j=0;i<len;i++) { if(v[org[i]]==0)v[org[i]]=++j; if(j==NC)break; } for(i=0;i<N;i++) now=now*NC+v[org[i]]; ans++;hash[now]=1; int t=pow(NC,N-1); for(j=0,i=N;i<len;i++,j++) { now-=t*v[org[j]]; now=now*NC+v[org[i]]; if(hash[now]!=0)continue; hash[now]=1;ans++; } return ans; } int main() { scanf("%d%d%s",&N,&NC,org); printf("%d\n",find()); return 0; }
import java.util.HashMap; import java.util.Scanner; public class Main { private static Scanner in; public static void main(String[] args) { HashMap<String, Boolean> vis=new HashMap<String,Boolean>(); in = new Scanner(System.in); @SuppressWarnings("unused") int N=in.nextInt(),NC=in.nextInt(); String s=in.next(),t; int i,j,len=s.length(),ans=0; for(i=N,j=0;i<=len;i++,j++) { t=s.substring(j, i); if(vis.containsKey(t)==true) continue; vis.put(t, true); ans++; } System.out.println(ans); } }
import java.util.HashMap; import java.util.Scanner; public class Main { private static Scanner in; public static void main(String[] args) { HashMap<String, Boolean> vis=new HashMap<String,Boolean>(); in = new Scanner(System.in); @SuppressWarnings("unused") int N=in.nextInt(),NC=in.nextInt(); String s=in.next(),t; int i,j,len=s.length(),ans=0; for(i=N,j=0;i<=len;i++,j++) { t=s.substring(j, i); if(vis.containsKey(t)==true) continue; vis.put(t, true); ans++; } System.out.println(ans); } }