Leetcode #30. Substring with Concatenation of All Words 连续子串查找 解题报告

来源:互联网 发布:java split多个分隔符 编辑:程序博客网 时间:2024/06/14 05:28

1 解题思想

题目说给了一个原串,然后给了一组单词,让你从这个原串当中找一个区间,这个区间正好包含了这些所有的单词,不能交叉,不能有多余的值

这道题是我在Leetcode 刷的最艰辛的一道题,我可能不适合这种风格的,最后我给的AC代码,有时候也可能会超时

网上有说做法是用滑动窗口。。可能吧。。我看不懂

所以我就是用了一个低级滑动窗口。。然后使用哈希加速,窗口期间按照顺序查看是否存在,是否满足条件,不满足的话就移动。。有点蠢?

2 原题

Substring with Concatenation of All Words
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:
s: “barfoothefoobarman”
words: [“foo”, “bar”]

You should return the indices: [0,9].
(order does not matter).

3 AC解

public class Solution {    /**     * 两个指针 解法不太好     * **/    public List<Integer> findSubstring(String s, String[] words) {        HashMap<String,Integer> map=new HashMap<String,Integer>();        List<String> allwords=new ArrayList<String>();        int n=s.length(),m=words.length,len=words[0].length();        int i,j,k;        for(i=0;i<m;i++){            if(map.containsKey(words[i])){                map.put(words[i],map.get(words[i])+1);            }            else{                map.put(words[i],1);            }        }        for( i=0;i<=n-len;i++){            allwords.add(s.substring(i,i+len));        }        HashMap<String,Integer> tmpMap=(HashMap<String,Integer>)map.clone();        int start=0,end=0;        List<Integer> list=new ArrayList<Integer>();        while(start<=n-m*len ){            if(end-start==m*len){                list.add(start);                start++;                while(start<=n-m*len  && map.containsKey(allwords.get(start))==false)                    start++;                end=start;                tmpMap=(HashMap<String,Integer>)map.clone();                continue;            }            String part=allwords.get(end);            if(tmpMap.containsKey(part) && tmpMap.get(part)>0){                tmpMap.put(part,tmpMap.get(part)-1);                end+=len;            }            else{                start++;                while(start<=n-m*len  && map.containsKey(allwords.get(start))==false)                    start++;                end=start;                tmpMap=(HashMap<String,Integer>)map.clone();            }        }        return list;    }}
0 0