7.算法笔记——详解前缀数和贪心算法

1.前缀树
  例子:
  一个字符串类型的数组arr1,另一个字符串类型的数组arr2。arr2中有哪些字符,是arr1中出现的?请打印。arr2中有哪些字符,是作为arr1中某个字符串前缀出现的?请打印。arr2
  中有哪些字符,是作为arr1中某个字符串前缀出现的?请打印 arr2中出现次数最大的前缀。
  
  代码:
  public static class TrieNode {
    public int path;
    public int end;
    public TrieNode[] nexts;
    public TrieNode() {
      path = 0;
      end = 0;
      nexts = new TrieNode[26]; //26个字母,若有更多的字符,可以使用HashMap
    }
  }
  
  public static class Trie {
    private TrieNode root;
    public Trie() {
      root = new TrieNode();
    }
    //插入操作
    public void insert(String word) {
      if (word == null) {
        return;
      }
      char[] chs = word.toCharArray();
      TrieNode node = root;
      int index = 0;
      for (int i = 0; i < chs.length; i++) {
        index = chs[i] - 'a';
        if (node.nexts[index] == null) {
          node.nexts[index] = new TrieNode();
        }
        node = node.nexts[index];
        node.path++;
      }
      node.end++;
    } 
    //删除操作
    public void delete(String word) {
      if (search(word) != 0) {  //查询是否存在才可开始删除
        char[] chs = word.toCharArray();
        TrieNode node = root;
        int index = 0;
        for (int i = 0; i < chs.length; i++) {
          index = chs[i] - 'a';
          if (--node.nexts[index].path == 0) {
            node.nexts[index] = null;
            return;
          }
          node = node.nexts[index];
        }
        node.end--;
      } 
    }
    //查询一条字符串插入了几次
    public int search(String word) {

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值