【題目描述】
Given a string source and a string target, find the minimum window in source which will contain all the characters in target.
Notice:If there is no such window in source that covers all characters in target, return the emtpy string "".If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in source.
給定一個字符串source和一個目標字符串target篡悟,在字符串source中找到包括所有目標字符串字母的子串倦蚪。
注意:如果在source中沒有這樣的子串,返回""蓬痒,如果有多個這樣的子串,返回起始位置最小的子串盟步。
【題目鏈接】
http://www.lintcode.com/en/problem/minimum-window-substring/
【題目解析】
可以用窗口型兩個指針的思路來解決米绕,外層for循環(huán)i = 0 ... n, 內(nèi)層while循環(huán),條件是j < source.length() 和 !isValid(sourceHash, targetHash)末荐,前者是數(shù)組下標邊界,后者是一個函數(shù)新锈,檢查當前窗口中的substring是否包含了目標字符串中全部所需的字符甲脏,未滿足則繼續(xù)擴大窗口j++,同時更新sourceHash妹笆。這里sourceHash块请,targetHash是整型數(shù)組int[],因為ASCII碼最多256個拳缠,因此用int[]可以作為簡化的HashMap使用墩新,key是char對應的int的值,value則是該char在substring中的出現(xiàn)個數(shù)窟坐。isValid函數(shù)則檢查sourceHash是否全部包含了targetHash海渊,256個字符一一對應绵疲,因此只需一重for循環(huán),如果sourceHash[i] < targetHash[i]臣疑,則說明有字符未滿足條件盔憨。
需要注意的是,要設(shè)定一個輔助變量記錄minStr的長度讯沈。
【參考答案】