Advertisement
heavenriver

2011_06_21.java (ex. 2)

Jan 1st, 2013
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. // Esame del 21 giugno 2011, esercizio 2
  2. // Ricordarsi di specificare sempre, nei commenti al codice, l'utilità di ogni metodo.
  3.  
  4. class Node<E>
  5.     {
  6.     E elem;
  7.     LinkedList<Node<E>> children;
  8.     public Node(E elem);
  9.     public E getElem();
  10.     public LinkedList<Node<E>> children();
  11.     }
  12.  
  13. class Tree<String>
  14.     {
  15.     Node<String> root;
  16.     public Tree(String s);
  17.     public Node<String> root();
  18.     public Node<String> remove(Node<String> n);
  19.     public boolean isExternal();
  20.     public String replace(Node<String> n, String s);
  21.     public boolean isEmpty();
  22.    
  23.     public boolean startWith(Node root, String prefix) // Costo computazionale Theta(n) per definizione
  24.         {
  25.         boolean ret = false;
  26.         startWith(root, prefix, "", 0, ret);
  27.         return ret;
  28.         }
  29.     public boolean startWith(Node n, String prefix, String s, int pos, boolean ret)
  30.         {
  31.         if(s.equals(prefix))
  32.             {
  33.             ret = true;
  34.             return;
  35.             }
  36.         if(n.isExternal() || n.children().size() >= pos) return;
  37.         if(!n.isExternal() && n.children().size() < pos)
  38.             {
  39.             s = s.concat(n.children().get(pos));
  40.             startWith(n.children().get(pos), prefix, s, 0, ret);
  41.             }
  42.         startWith(n, prefix, s, pos + 1, ret);
  43.         }
  44.    
  45.     public void remove(String s) // Stimato O(n*h) perché può effettuare fino a n/k rimozioni ciascuna di costo h
  46.         {
  47.         remove(s, root);
  48.         }
  49.     public void remove(String s, Node<String> n)
  50.         {
  51.         if(n == null) return;
  52.         for(int i = 0; i < s.length(); i++)
  53.             {
  54.             if(n.getElem().equals(s.charAt(i)))
  55.                 {
  56.                 remove(n);
  57.                 return;
  58.                 }
  59.             }
  60.         for(Node<String> c : n.children())
  61.             remove(s, c);
  62.         }
  63.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement