Skip to content

Instantly share code, notes, and snippets.

@RakhmedovRS
Created September 25, 2024 04:19
Show Gist options
  • Select an option

  • Save RakhmedovRS/c8330b5e33b8cec091da27057e9ef2d1 to your computer and use it in GitHub Desktop.

Select an option

Save RakhmedovRS/c8330b5e33b8cec091da27057e9ef2d1 to your computer and use it in GitHub Desktop.
FinDev task
public class ParseString2 {
//stores mapping key -> string array of value and index in original string
Map<String, List<String>> cache = new HashMap<>();
//stores mapping index of key-value pair in original string -> key and position of value in list inside of cache
Map<String, String[]> reverseCache = new TreeMap<>();
public void parse(String str) {
String[] keyValuePairs = str.split(";");
for (int i = 0; i < keyValuePairs.length; i++) {
String[] keyValue = keyValuePairs[i].split("=");
String key = keyValue[0];
String value = keyValue[1];
List<String> cacheValues = cache.computeIfAbsent(key, k -> new ArrayList<>());
cacheValues.add(value);
String indexString = String.valueOf(i);
reverseCache.computeIfAbsent(indexString, k -> new String[]{key, String.valueOf(cacheValues.size() - 1)});
}
}
// No cache for original str
public String getOriginal() {
List<String> keyValuePairs = new ArrayList<>();
reverseCache.values().forEach(keyAndIndex -> {
String key = keyAndIndex[0];
int index = Integer.parseInt(keyAndIndex[1]);
String value = cache.get(key).get(index);
keyValuePairs.add(key + "=" + value);
}
);
return keyValuePairs.stream().collect(Collectors.joining(";"));
}
// O(1)
public String getValues(String key) {
if (cache.containsKey(key)) {
List<String> values = cache.get(key);
return values.get(values.size() - 1);
}
return null;
}
public static void main(String[] args) {
String val = "key1=val1;key2=val2;key3=val3;key1=val4;key2=val6;key1=val6";
ParseString2 ps = new ParseString2();
ps.parse(val);
System.out.println(ps.getOriginal());
System.out.println(ps.getValues("key1"));
System.out.println(ps.getValues("key2"));
System.out.println(ps.getValues("key3"));
System.out.println(ps.getValues("342342"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment