Java using hashmap for searching string

Viewed 72

Is it possible to compare characters from a string and print out the position of the first unique one? Is there maybe something from the String class that can help me do this?

Pseudocode:

enter code here
String s = "ABC456";
int n = 2;


ArrayList<String> str = new ArrayList<>();
Map<String, Long> counts2 = new LinkedHashMap<String, 
Long>();
for(String val : str){
    long count = counts2.getOrDefault(val, 0L);
    counts2.put(val, ++count);
}
for(String key: counts2.keySet()){
    if(counts2.get(key)==1){
        System.out.println(list.indexOf(key));
        break;
    }
}
1 Answers

Please try mine:

import java.util.HashSet;
import java.util.HashMap;
import java.util.LinkedHashSet;


public class Main {

  public static void main(String[] args) {
    String originalString = "AAAB"; //little trickier input! ;)
    int n = 1;

    LinkedHashSet<String> uniques = new LinkedHashSet<>();
    HashSet<String> dupes = new HashSet<>();
    HashMap<String, Integer> str2Idx = new HashMap<>();

    for (int cur = 0; cur <= originalString.length() - n; cur++) {

      String substr = originalString.substring(cur, cur + n);

      if (uniques.contains(substr)) { // cleanup
        uniques.remove(substr);
        str2Idx.remove(substr);
        dupes.add(substr);
      } else if(!dupes.contains(substr)){ // store
        uniques.add(substr);
        str2Idx.put(substr, cur);
      }
    }
    // when the input is "external"/unknown, we should also avoid:
    if (uniques.isEmpty()) {
      System.out.println(-1);
    } else {
      // Print(get the index of (first element of uniques))
      System.out.println(str2Idx.get(uniques.iterator().next()));
      // Prints "3" with the given input
    }
  }
}

So basically:

  • a LinkedHashSet for unique substrings.

    • "Linked": preserves order
    • and "Hash": makes contains operation faster
  • a HashMap<String, Integer, as the (variable) name suggest:

    • With (unique) substrings as keys
    • and their index (of first occurrence) as value
  • an additional "dupes" storage, to avoid re-adding.

Please test it deeper.

Related