简体   繁体   English

我怎么知道HashMap中的所有值都被访问过一次?

[英]How should I get know that all values in HashMap is visited once?

Here, I'm trying to find shortestSubstring from a string and i'm not able to find a way of how should i get to know if all the values of hashmap is visited once or not in O(1), or is there any another way to do it? 在这里,我试图从一个字符串中找到shortestSubstring,我无法找到一种方法,如何知道是否在O(1)中访问过一次hashmap的所有值,或者是否有任何值另一种方式呢?

String mainString = "abacbbdabc";
String targetString = "adc"; 

HashMap will iterate and updating values until it find out all the characters from the targetString ie first substring will be from index 0 to 6 HashMap将迭代并更新值,直到它找到targetString所有字符,即第一个子字符串将从索引0 to 6

public String findShortestSubstring(String mainString, String targetString) {
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < targetString.length(); i++) {
            map.put(targetString.charAt(i), 1);
        }

        for (int i = 0; i < mainString.length(); i++) {
            if (map.containsKey(mainString.charAt(i))) {
                map.put(mainString.charAt(i), 0);
            }
        }
        return null;
    }

If I do understand properly: 如果我理解得当:

I would use ArrayList. 我会使用ArrayList。 Try to split on single letter every element into list. 尝试将每个元素的单个字母拆分为列表。 For example 例如

mainString=skldfjkldfgj; // split it ["s","k","l","d","f","j","k","l","d","f","g","j"]
targetString=dfj;  //split it too ["d","f","j"]

You know dfj is split into 3 elements into ArrayList. 你知道dfj被分成3个元素到ArrayList中。 If you find first letter of targetString in mainString then check next 2 elements if they matches. 如果在mainString中找到targetString的第一个字母,则检查接下来的2个元素是否匹配。

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

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