Substring with Concatenation of All Words

来源:互联网 发布:好看的小说言情 知乎 编辑:程序博客网 时间:2024/06/03 14:51

参考小莹子同学的点击打开链接

自己刚才一直在纠结这段code,其实就是保证还剩下最后一个当前满足条件的word能留下。

if (curDict.get(temp) < dict.get(temp)) {                            count--;                        }

ArrayList<Integer> list = findSubstring("barfoofoobarthefoobarman",new String[]{"foo", "bar","the"});

用这个测一下吧。

public class Solution {    public List<Integer> findSubstring(String s, String[] words) {        List<Integer> res = new LinkedList<>();        if (s == null || s.length() == 0 || words == null || words.length == 0) {            return res;        }        int num = words.length;        Map<String, Integer> dict = new HashMap<>();        for (String word: words) {            if (dict.containsKey(word)) {                dict.put(word, dict.get(word) + 1);            } else {                dict.put(word, 1);            }        }        int wordLen = words[0].length();        for (int i = 0; i < wordLen; i++) {            int index = i;            int count = 0;            Map<String, Integer> curDict = new HashMap<>();            //for (int j = i; j < s.length() - wordLen; j = j + wordLen) {            for (int j = i; j <= s.length() - wordLen; j = j + wordLen) {                String word = s.substring(j, j + wordLen);                if (!dict.containsKey(word)) {                    //index = j;                    index = j + wordLen;                    curDict.clear();                    count = 0;                    continue;                }                                if (curDict.containsKey(word)) {                    curDict.put(word, curDict.get(word) + 1);                } else {                    curDict.put(word, 1);                }                if (curDict.get(word) <= dict.get(word)) {                    count++;                } else {                    while (curDict.get(word) > dict.get(word)) {                        String temp = s.substring(index, index + wordLen);                        curDict.put(temp, curDict.get(temp) - 1);                        if (curDict.get(temp) < dict.get(temp)) {                            count--;                        }                        index = index + wordLen;                    }                }                if (count == num) {                    res.add(index);                    String temp = s.substring(index, index + wordLen);                    curDict.put(temp, curDict.get(temp) - 1);                    count--;                    index = index + wordLen;                }            }        }        return res;    }}




0 0
原创粉丝点击