shortest unique prefix

Given an array of words, find all shortest unique prefixes to represent each word in the given array. Assume that no word is prefix of another.

Input: arr[] = {"zebra", "dog", "duck", "dove"}
Output: dog, dov, du, z
Explanation: dog => dog
             dove = dov 
             duck = du
             z   => zebra 

Input: arr[] =  {"geeksgeeks", "geeksquiz", "geeksforgeeks"};
Output: geeksf, geeksg, geeksq}

思路:用trie来build字典,build的时候count一下每个字符出现的次数,然后对每个string进行查询,第一count为1的node,即可返回shortest prefix了。

public class shortestPrefix {
  private TrieNode root;
  public shortestPrefix() {
    root = new TrieNode();
  }

   public static void main(String[]  args) {
     String strs[] = {"zebra", "dog", "duck", "dove"};
     shortestPrefix p = new shortestPrefix();
     p.findShortestPrefix(strs);
   }

  public void insert(String word) {
    if(word == null || word.length() == 0) return;
    TrieNode curNode = root;
    for(int i=0; i<word.length(); i++) {
      char c = word.charAt(i);
      int index = c-'a';
      if(curNode.array[index] == null){
        TrieNode temp = new TrieNode();
        curNode.array[index] = temp;
        curNode = temp;
        curNode.count = 1;
      } else {
        curNode.array[index].count++;
        curNode = curNode.array[index];
      }
    }
    curNode.isword = true;
  }

  public  void findShortestPrefix(String[] strs) {
    // build trie;
    for(int i=0; i<strs.length; i++) {
      String str = strs[i];
      insert(str);
    }

    // find shortest prefix;
    for(int i=0; i<strs.length;i++){
      String str = strs[i];
      TrieNode curNode = root;
      StringBuilder sb = new StringBuilder();
      for(int j=0; j<str.length(); j++){
        char c = str.charAt(j);
        int index = c-'a';
        if(curNode.array[index].count == 1){
          sb.append(c);
          System.out.println(sb.toString());
          break;
        } else {
          sb.append(c);
          curNode = curNode.array[index];
        }
      }
    }
  }

  public class TrieNode {
    public TrieNode[] array;
    public int count = 0;
    public boolean isword;

    public TrieNode() {
      array = new TrieNode[26];
    }
  }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值