[LeetCode]30.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.

Example 1:數組

Input: s = "barfoothefoobarman", words = ["foo","bar"] Output:
[0,9] Explanation: Substrings starting at index 0 and 9 are "barfoor"
and "foobar" respectively. The output order does not matter, returning
[9,0] is fine too. Example 2:數據結構

Input: s = "wordgoodgoodgoodbestword", words =
["word","good","best","word"] Output: []優化

思路是經過indexOf找到最靠前的那個,而後經過每一個數組判讀是否是符合狀況。這樣想起來很亂
應該是先在腦海中構建出暴力解法,也就是當index到i時,判斷i以前加上i以前的狀況是否知足條件。i以前的狀況能夠提早保存下來,達到優化的目的。
還有考察點就是數據結構,這個結構須要知足查詢是o1,且能保留加入的順序,最開始咱們採用的結構式LinkedHashSet,可是沒有注意到words裏的順訓是能夠重複的.
能夠整理下咱們須要的數據結構
1.能保留添加順序
2.能夠判斷是否是無順序的
可使用LinkedHashMap
可是對他的equals不是很滿意
還有沒法知道他包含元素的個數,須要另一個數組保存
後來否認了這個思路,這樣會有一個Bug,LinkedHashMap 添加兩次相同數據後,第二次添加時候的順序反應的是不許確的
仍是使用兩個數據結構,一個LinkedList和HashMapcode

public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> list=new ArrayList();
        int a=words.length;
        if(a<=0) return list;
        int b=words[0].length();
        if(b<=0) return list;
        int len=s.length();
        HashMap<String,Integer> target=new HashMap();
        for(String s1:words) target.compute(s1,(k,v)->v==null?1:v+1);
        LinkedList[] linkeds=new LinkedList[len];
        HashMap[] maps=new HashMap[len];
        for(int i=0;i<=len-b;i++){
            LinkedList<String> linked;
            HashMap<String,Integer> map;
            if(i>=b){
                linked=linkeds[i-b];
                map=maps[i-b];
                if(linked.size()>=a) {
                    String first=linked.removeFirst();
                    if(map.get(first)>1) map.put(first,map.get(first)-1);
                    else map.remove(first);
                }
            }else{
                linked=new LinkedList();
                map=new HashMap();
            }
            String s1=s.substring(i,i+b);
            if(target.containsKey(s1)){
                linked.addLast(s1);
                map.compute(s1,(k,v)->v==null?1:v+1);
            }else{
                map.clear();
                linked.clear();
            }
            if(map.equals(target)) list.add(i-(a-1)*b);
            linkeds[i]=linked;
            maps[i]=map;
        }
        return list;
}
相關文章
相關標籤/搜索