I am to initialize what is called an LZWDictionary to have an initial set of entries taken from the set of unique characters in a provided string.
Unique characters are added to a map as they are encountered in the provided input string, with an increasing index value (beginning at index 0). At the same time, the characters are added to a list. The indices associated with each dictionary entry in the map thus relate to their index (position) in the list.
Here is the code that I tried with comments on my thought process.
// Initialising map
map = new LinkedHashMap<>();
// Initialising list
list = new ArrayList<>();
// Declaring String variable for holding character
String str;
// Declaring index variable for holding Value
int index;
// If block for checking empty string.
if (characters.length() == 0)
// Throwing IllegealArgumentException if String is empty.
throw new IllegalArgumentException("Input should not be empty!!!");
else {
// Iterating over the String
for (int i = 0; i < characters.length(); i++) {
// Taking particular character in the Iteration
str = "" + characters.charAt(i);
// Checking value of a particular character in the map
if (map.get(str) == null) {
// If not present in map, then add that to the map and list
map.put(str, 1);
list.add(str);
}
else {
index = map.get(str);
map.replace(str, index + 1);
}
}
}
I am getting a java.lang.AssertionError where the index value for "a" is not correct in map expected<0> but was <5>. The sample code is:
LZWDictionary act = new LZWDictionary("ababababa");
List<String> exp = Arrays.asList("a","b");
str = "" + characters.charAt(i)is better written asstr = characters.substring(i, i + 1)