Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Anagram Detector

/** Checks if two words are anagrams or not
*
@param firstWord
*
@param secondWord
*/
public static boolean areAnagram(String firstWord, String secondWord) {

int numberOfUnique = 0;
int processed = 0;
if (firstWord.length() != secondWord.length()) {
return false;
}
int[] chars = new int[256];
for (int i = 0; i < firstWord.length(); i++) {
if (chars[firstWord.charAt(i)] == 0) {
numberOfUnique
++;
}
chars[firstWord.charAt(i)]
++;
}
for (int i = 0; i < secondWord.length(); i++) {
// this char is not there so false
if (chars[secondWord.charAt(i)] == 0)
return false;

chars[secondWord.charAt(i)]
--;

if (chars[secondWord.charAt(i)] == 0) {
processed
++;
if (numberOfUnique == processed) {
System.out.println(processed);
return secondWord.length() == processed + 1;
}
}

}

Remove duplicate Characters without extra memory in java

/**
* Without using extra(large) memory Complexity O(n^2)
*
@param word
*/
private static void removeDuplicates(char[] word) {
int currentIndex = 1;
for (int i = 0; i < word.length; i++) {
int j;
for (j = 0; j < currentIndex; j++) {
if (word[i] == word[j]) {
break;
}
}
if (currentIndex == j) {
word[currentIndex
++] = word[i];
}

}
while (currentIndex < word.length) {
word[currentIndex
++] = ' ';
}
}

Flyweight


Share objects when they are common some common examples are from the JDK
Integer and String objects
The object is restricted to be created through the factory and the object is shared.
/*

 public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
*/

Search 24 Bytes