简体   繁体   English

Java 使用 hashmap 搜索字符串

[英]Java using hashmap for searching string

Is it possible to compare characters from a string and print out the position of the first unique one?是否可以比较字符串中的字符并打印出第一个唯一字符的 position? Is there maybe something from the String class that can help me do this?字符串 class 是否有一些东西可以帮助我做到这一点?

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

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.用于唯一子字符串的LinkedHashSet

    • "Linked": preserves order “已链接”:保留顺序
    • and "Hash": makes contains operation faster和“哈希”:使contains操作更快
  • a HashMap<String, Integer , as the (variable) name suggest:一个HashMap<String, Integer ,正如(变量)名称所暗示的:

    • 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.请更深入地测试它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM