LeetCode Sliding Window 滑動(dòng)窗口 處理字符串子串查找匹配問(wèn)題

關(guān)于我的 Leetcode 題目解答,代碼前往 Github:https://github.com/chenxiangcyr/leetcode-answers


一個(gè)標(biāo)準(zhǔn) Sliding Window 模板:
引用:https://leetcode.com/problems/minimum-window-substring/discuss/26808/here-is-a-10-line-template-that-can-solve-most-substring-problems

int findSubstring(string s){
        vector<int> map(128,0);
        int counter; // check whether the substring is valid
        int begin=0, end=0; //two pointers, one point to tail and one  head
        int d; //the length of substring

        for() { /* initialize the hash map here */ }

        while(end < s.size()){

            if(map[s[end++]]-- ?){  /* modify counter here */ }

            while(/* counter condition */){ 
                 
                 /* update d here if finding minimum*/

                //increase begin to make it invalid/valid again
                
                if(map[s[begin++]]++ ?){ /*modify counter here*/ }
            }  

            /* update d here if finding maximum*/
        }
        return d;
  }

LeetCode題目:438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

class Solution {
    public List<Integer> findAnagrams(String s, String t) {
        List<Integer> result = new LinkedList<>();
        
        if(t.length()> s.length()) return result;
        
        /* initialize the hash map here */
        Map<Character, Integer> map = new HashMap<>();
        for(char c : t.toCharArray()){
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        
        // check whether the substring is valid
        int counter = map.size();
        
        //two pointers, one point to tail and one  head
        int begin = 0, end = 0;
        
        while(end < s.length()) {
            
            /* modify counter here */
            char c = s.charAt(end);
            if(map.containsKey(c)) {
                map.put(c, map.get(c) - 1);
                
                if(map.get(c) == 0) {
                    counter--;
                }
            }
            end++;
            
            /* counter condition */
            while(counter == 0) {
                // finding
                if(end - begin == t.length()){
                    result.add(begin);
                }
                
                /* moving sliding window */
                /* modify counter here */
                c = s.charAt(begin);
                if(map.containsKey(c)) {
                    map.put(c, map.get(c) + 1);
                    
                    if(map.get(c) > 0){
                        counter++;
                    }
                }
                begin++;
            }
            
        }
        return result;
    }
}

LeetCode題目:76. Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,

S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".

class Solution {
    public String minWindow(String s, String t) {
        if(s == null || s.length() < t.length() || s.length() == 0){
            return "";
        }
        
        /* initialize the hash map here */
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(char c : t.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        
         // check whether the substring is valid
        int counter = map.size();
        
        //two pointers, one point to tail and one  head
        int begin = 0, end = 0;
        
        int length = Integer.MAX_VALUE;
        int head = 0;
        
        while(end < s.length()) {
            
            /* modify counter here */
            char c = s.charAt(end);
            if(map.containsKey(c)) {
                map.put(c, map.get(c) - 1);
                
                if(map.get(c) == 0) {
                    counter--;
                }
            }
            end++;
                      
            /* counter condition */  
            while(counter == 0) {
                
                // finding
                /* update d here if finding minimum*/
                if(end - begin < length) {
                    length = end - begin;
                    head = begin;
                }
                
                /* moving sliding window */
                /* modify counter here */
                c = s.charAt(begin);
                if(map.containsKey(c)) {
                    map.put(c, map.get(c) + 1);
                    
                    if(map.get(c) > 0){
                        counter++;
                    }
                }
                begin++;
            }
        }

        return length == Integer.MAX_VALUE ? "" : s.substring(head, head + length);
        
    }
}

LeetCode題目:3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.length() == 0){
            return 0;
        }
        
        /* initialize the hash map here */
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        
        // check whether the substring is valid
        int counter = 0;
        
        //two pointers, one point to tail and one  head
        int begin = 0, end = 0;
        
        int length = Integer.MIN_VALUE;
        
        while(end < s.length()) {
            /* modify counter here */
            char c = s.charAt(end);
            map.put(c, map.getOrDefault(c, 0) + 1);
            if(map.get(c) > 1) {
                counter++;
            }
            end++;
            
            /* counter condition */  
            while(counter > 0) {
                /* moving sliding window */
                /* modify counter here */
                c = s.charAt(begin);
                map.put(c, map.get(c) - 1);
                if(map.get(c) > 0) {
                    counter--;
                }
                begin++;
            }
            
            /* update d here if finding maximum*/
            if(end - begin > length) {
                length = end - begin;
            }
        }
        
        return length;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末牧愁,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子风秤,更是在濱河造成了極大的恐慌努溃,老刑警劉巖劲装,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異兼雄,居然都是意外死亡吟逝,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門赦肋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)块攒,“玉大人,你說(shuō)我怎么就攤上這事佃乘〈丫” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵趣避,是天一觀的道長(zhǎng)庞呕。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么住练? 我笑而不...
    開(kāi)封第一講書人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任地啰,我火速辦了婚禮,結(jié)果婚禮上讲逛,老公的妹妹穿的比我還像新娘亏吝。我一直安慰自己,他們只是感情好盏混,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布蔚鸥。 她就那樣靜靜地躺著,像睡著了一般许赃。 火紅的嫁衣襯著肌膚如雪止喷。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,598評(píng)論 1 305
  • 那天混聊,我揣著相機(jī)與錄音弹谁,去河邊找鬼。 笑死技羔,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的卧抗。 我是一名探鬼主播藤滥,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼社裆!你這毒婦竟也來(lái)了拙绊?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤泳秀,失蹤者是張志新(化名)和其女友劉穎标沪,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體嗜傅,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡金句,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了吕嘀。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片违寞。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖偶房,靈堂內(nèi)的尸體忽然破棺而出趁曼,到底是詐尸還是另有隱情,我是刑警寧澤棕洋,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布挡闰,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏摄悯。R本人自食惡果不足惜赞季,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望射众。 院中可真熱鬧碟摆,春花似錦、人聲如沸叨橱。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)罗洗。三九已至愉舔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間伙菜,已是汗流浹背轩缤。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留贩绕,地道東北人火的。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像淑倾,于是被迫代替她去往敵國(guó)和親馏鹤。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容