AdSense

Showing posts with label Set. Show all posts
Showing posts with label Set. Show all posts

Monday, December 29, 2014

Find all the repeating sub-string sequence

Find all the repeating sub-string sequence of specified length in a large string sequence. The sequences returned i.e. the output must be sorted alphabetically. 

For e.g. 

Input String: "ABCACBABC" 
repeated sub-string length: 3 

Output: ABC 

Input String: "ABCABCA" 
repeated sub-string length: 2 

Output: AB, BC, CA

Click here for the original problem.
Ha, very interesting problem. I was wondering why all the add() methods returns boolean type. Now I  know, since Set doesn't allow duplicate values,  if add() returns false, it means the set fails to add the value, which probably imply there already exists the value. And in this problem, we are utilizing this feature.


import java.util.*;
public class RepeatingSubstring {
 public ArrayList repeatSubstring (String s, int length) {
  if (s == null)
   throw new NullPointerException("Null array");
  ArrayList rst = new ArrayList ();
  if (s.length() == 0)
   return rst;
  HashSet nonRepeating = new HashSet ();
  TreeSet repeating = new TreeSet ();
  for (int i = 0; i + length <= s.length(); i++) {
   if (!nonRepeating.add(s.substring(i, i + length)))
    repeating.add(s.substring(i, i + length));
  }
  rst = new ArrayList (repeating);
  return rst;
 }

}

Saturday, December 13, 2014

Sets: HashSet, TreeSet and LinkedHashSet

Summarized from http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/ 


A Set contains no duplicate elements. There are three commonly used implementations of Set" HashSet, TreeSet and LinkedHashSet. 

Set interface extends Collection interface. In a set, no duplicates are allowed. If a duplicate element is inserted, the original element will be removed from the set. 

HashSet is implemented using a hash table (beautiful invention!). Elements are not ordered. The add, remove and contains methods have O(1) complexity. 

TreeSet is implemented using a tree structure. The elements in a set are sorted. The add, remove and contains methods have O(log(n)) complexity. It offered methods to deal with ordered set like first(), last(), headSet(), tailSet(), etc. 

To define a class, because TreeSet is sorted, the corresponding object need to implement java.lang.Comparable's compareTo(). 

class XXX implements Comparable<Dog>
{
...
public int compareTo(Object o)
{
...
}
}

And the output of the object will be ordered. 

LinkedHashSet is between HashSet and TreeSet. It is implemented as a hash table with a linked list running through it, so it provides the order of insertion. The time complexity of basic methods is O(1).