zoukankan      html  css  js  c++  java
  • 字典树(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:给你一个单词集合,支持添加,删除,询问以某个字符串为前缀的单词个数

  • 相关阅读:
    vue 交互 跨域获取数据
    计算属性computed缓存 与 methods 的思考
    _this 与 this
    python 占位符 %s Format
    odoo 中字段属性对象Field
    安装CentOS7.7图解
    docker的volumes
    Docker常用命令详解
    Ubuntu修改时区和更新时间
    SqlServer创建时间维度
  • 原文地址:https://www.cnblogs.com/ljc20020730/p/7210299.html
Copyright © 2011-2022 走看看