Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ code is added instead of the Java code in StriversTrieSeries/L3_Complete_String_Java #3

Open
KPrakriti opened this issue Jan 17, 2022 · 0 comments

Comments

@KPrakriti
Copy link

KPrakriti commented Jan 17, 2022

Please add the Java code.

//Updated : Here is the working java code for this problem -

class Node{
    Node links[] = new Node[26];
    boolean flag = false;
    
    public Node(){
        
    }
    boolean containsKey(char ch)
    {
        return (links[ch -'a'] != null);
    }
    
    void put(char ch, Node node)
    {
        links[ch-'a'] = node;
    }
    Node get(char ch)
    {
        return (links[ch-'a']); // ch -'a' gives corresponding ascii of the particular alphabet
    }
    void setEnd()
    {
        flag = true;
    }
    boolean isEnd()
    {
        return flag;
    }
};
 class Trie{
     private static Node root;
     //whenever we require object of this trie we know we'll be needing a new trie 
     Trie(){
         root = new Node();
     }
     public static void insert(String word)
     {
         Node node = root;
        for(int i = 0;i<word.length();i++) 
        {
            if(!node.containsKey(word.charAt(i))) {
                node.put(word.charAt(i), new Node()); 
            }
            node = node.get(word.charAt(i)); 
        }
        node.setEnd(); 
     }
      boolean checkIfAllPrefixExists(String word) 
      {
        Node node = root;
        boolean flag = true; 
        for(int i = 0;i<word.length() && flag;i++) {
            if(node.containsKey(word.charAt(i))) {
                node = node.get(word.charAt(i)); 
                flag = flag & node.isEnd(); 
            }
            else {
                return false; 
            } 
        }
        return flag; 
    }
 }
class Solution {

  public static String completeString(int n, String[] a) {
    Trie obj = new Trie();
      for(int i =0; i<n; i++)
      {
          obj.insert(a[i]);
      }
      String longest = "";
      for(int i= 0; i<n; i++)
      {
          if(obj.checkIfAllPrefixExists(a[i]))
          {
              if(a[i].length() > longest.length())
              {
                  longest = a[i]; 
              }
               else if(a[i].length() == longest.length() && a[i].compareTo(longest) < 0) 
               {
                longest = a[i]; 
               }
          }
      }
      if(longest == "") return "None"; 
    return longest;

  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant