[英]Java using hashmap for searching string
是否可以比較字符串中的字符並打印出第一個唯一字符的 position? 字符串 class 是否有一些東西可以幫助我做到這一點?
偽代碼:
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;
}
}
請試試我的:
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
}
}
}
所以基本上:
用於唯一子字符串的LinkedHashSet
。
contains
操作更快一個HashMap<String, Integer
,正如(變量)名稱所暗示的:
額外的“重復”存儲,以避免重新添加。
請更深入地測試它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.