1. 程式人生 > >乘風破浪:LeetCode真題_030_Substring with Concatenation of All Words

乘風破浪:LeetCode真題_030_Substring with Concatenation of All Words

乘風破浪:LeetCode真題_030_Substring with Concatenation of All Words

一、前言

   這次我們還是找字串的索引,不過,需要將另一個字串列表中的字串拼接起來,要求全部都拼接並且出現且僅出現一次,然後在字串中求子串的起始位置。

二、Substring with Concatenation of All Words

2.1 問題

2.2 分析與解決

    其實我們仔細想一下,求子串的索引可以使用工具庫來解決,重要的是將字串列表中的字串進行組合,假設一共N個字串,那麼有N*(N-1)*...*(1)中組合方式,但是還要考慮到重複的問題,然後求子串即可。這讓我們想到了是否可以使用遞迴來進行組合,這一點是可以的,於是我們在不考慮重複的情況下可以得到解答,就算重複了,最後去除重複的起始點只保留一個即可。這是一種笨辦法。

    當然我們還有其他的解法,我們可以通過HashMap的特性,將列表放入其中,然後從字串s進行遍歷,同樣的將s進行剪裁和封裝,然後進行比較,如果相等則記錄索引,就這樣遍歷完s就可以得到結果了。

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> res = new LinkedList<>();
        if(s.length()==0 || words.length==0) 
            return new ArrayList<>();
        HashMap<String,Integer> hs = new HashMap<>();
        for (String w:words) 
            hs.put(w,hs.getOrDefault(w,0)+1);
        int wl = words[0].length();
        int wLen = words.length*words[0].length();
        for (int i = 0 ; i +wLen<=s.length();i++)
        {
            String curS = s.substring(i,i+wLen);
            HashMap<String,Integer> h = new HashMap<>();
            for (int j = 0 ; j <curS.length();j+=wl)                     
                h.put(curS.substring(j,j+wl),h.getOrDefault(curS.substring(j,j+wl),0)+1);
            if (h.equals(hs)) 
                res.add(i);
        }
        return res;
    }
}

 

三、總結

    通過java的一些特性,我們更快的求得了結果。