I have a method which looks for the smallest substring
from the input string which contains group of A
, C
, G
, T
letters.
My question has nothing to do with the algorithm.
I would like to keep original HashMap
and assign it to the modified map at the end of the outer for-loop, but the original HashMap
is modified even though I never modify the originalMap
in the code.
I am not sure if I am doing wrong.
Code:
void find2(String string) {
int n = string.length();
int occurrence = n / 4;
Map<Character, Integer> cache = new HashMap<Character, Integer>();
char[] original = { 'A', 'C', 'G', 'T' };
for (char c : original) {
cache.put(c, 0);
}
char[] chars = string.toCharArray();
char[] modifiableChars = string.toCharArray();
HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();
for (int ii = 0; ii < string.length(); ii++) {
char currentChar = chars[ii];
if (!countMap.containsKey(currentChar)) {
countMap.put(currentChar, 1);
} else {
Integer count = countMap.get(currentChar);
count++;
countMap.put(currentChar, count);
}
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
HashMap<Character, Integer> originalMap = new HashMap<Character, Integer>();
for (int ii = 0; ii < string.length(); ii++) {
char c = string.charAt(ii);
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
Integer count = map.get(c);
count++;
map.put(c, count);
}
if (!originalMap.containsKey(c)) {
originalMap.put(c, 1);
} else {
Integer count = originalMap.get(c);
count++;
originalMap.put(c, count);
}
}
int min = 0;
for (int i = 0; i < chars.length; i++) {
int change = 0;
int checkCount = countMap.get(chars[i]);
if (checkCount <= occurrence) {
continue;
}
boolean isValidated = false;
int j = i;
for (j = i; j < chars.length; j++) {
char c = chars[j];
int count = map.get(c);
if (count > occurrence) {
}
char nextChar = getNextChar(map, cache, occurrence);
if (nextChar == ' ') {
continue;
}
Integer nextCharCount = map.get(nextChar);
nextCharCount++;
map.put(nextChar, nextCharCount);
chars[j] = nextChar;
if (c != nextChar) {
Integer currentCount = map.get(c);
currentCount--;
map.put(c, currentCount);
}
change++;
// validate the characters.
if (isValid(chars, occurrence)) {
isValidated = true;
break;
}
}
if (isValidated) {
if (min == 0) {
min = change;
} else {
min = Math.min(min, change);
}
}
chars = string.toCharArray();
map = originalMap; // <--------
}
System.out.println(min);
}