Home > OS >  Java using hashmap for searching string
Java using hashmap for searching string

Time:09-11

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;
    }
}

CodePudding user response:

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.

CodePudding user response:

I had already provided you with code in an earlier post you created the other day which allows you to split the Original String ("ABC456") into whatever substring chunks size you like. Whether or not you have chosen to use that code is of course entirely up to you.

You can use a couple for loops to retrieve the Unique sub-strings contained within your String[] array (or whatever you've stored them in...your code changes hourly). In the below code the determined Unique Sub-Strings are placed into a List of String (List<String>). To get the sub-string index position within the Original String the String.indexOf() method is used:

String originalString = "ABC456";
int n = 2;
String[] strArray = {"AB", "BC", "C4", "45", "56"};
    
/* Determine all UNIQUE substrings within the strArray. All
   unique substrings are placed into the uniqueSubstrings 
   list:                                            */
List<String> uniqueSubstrings = new ArrayList<>();
boolean isUnique;
for (int i = 0; i < strArray.length; i  ) {
    isUnique = true;
    for (int j = 0; j < strArray.length; j  ) {
        if (i != j && strArray[i].equals(strArray[j])) {
            isUnique = false;
            break;
        }
    }
    if (isUnique) {
        uniqueSubstrings.add(strArray[i]);
    }
}
    
/* Get Index positions of the Unique Substrings 
   as found in the Original String.        */
if (uniqueSubstrings.isEmpty()) {
    System.out.println("There are no Unique Substrings to process!");
}
else {
    for (String str : uniqueSubstrings) {
        int fromIndex = originalString.indexOf(str);
        int toIndex = fromIndex   (n - 1);
        System.out.println("Unique: "   str   
                " - From Index: "   fromIndex   " To Index: "   toIndex);
    }
}
  • Related