字典树(trie树)的指针简单实现pascal

问题1:给你一个单词集合,支持添加,删除,询问某个单词出现次数。

const maxword=100;
      maxn=100;
type
 dictree=^rec;
 rec=record
 next:array[1..maxword]of dictree;
 val:boolean;
 cnt:longint;
end;
var a:array[1..maxn]of rec;
    root:dictree;
    i,n:longint;
    s:string;
    ch:char;
procedure delete(s:string);
var  p,newnode:dictree;
     x,i,j:longint;
begin
  p:=root;
 for i:=1 to length(s) do begin
  x:=ord(s[i]);
  if (p^.next[ord(s[i])]=nil) then exit
  else p:=p^.next[x];
 end;
 p^.cnt:=0;
 p^.val:=false;
end;
procedure insert(s:string);
  var p,newnode:Dictree;
      x,i,j:integer;
begin
  p:=root;
  for i:=1 to length(s) do begin
    x:=ord(s[i]);
    if p^.next[ord(s[i])]=nil then begin
       new(newnode);
       for j:=1 to maxn do newnode^.next[j]:=nil;
       p^.next[x]:=newnode;
       p:=newnode;
    end else p:=p^.next[x];
  end;
  inc(p^.cnt);
end;
function find(s:string):longint;
var p:dictree;
    i,x:longint;
begin
  p:=root;
  for i:=1 to length(s) do begin
    x:=ord(s[i]);
    if p^.next[ord(s[i])]=nil then EXIT(0)
     else p:=p^.next[x];
  end;
  exit(p^.cnt);
end;
begin
 new(root);
 root^.cnt:=0;
 fillchar(root^.cnt,sizeof(root^.cnt),0);
  writeln('// A:ADD.');
  writeln('// D:DELETE.');
  writeln('// Q:QUERY.');
 readln(n);
 for i:=1 to n do begin
  readln(ch);
  readln(s);
  case ch of
   'A':insert(s);
   'D':delete(s);
   'Q':writeln(find(s));
  end;
 end;
end.

问题2:给你一个单词集合,支持添加,删除,询问以某个字符串为前缀的单词个数

 

转载于:https://www.cnblogs.com/ljc20020730/p/7210299.html

你可能感兴趣的:(字典树(trie树)的指针简单实现pascal)