LeetCode 76 minimum window substring
2017-01-01 20:09
495 查看
Find the smallest window in a string containing all characters of another string
原文地址:http://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/
leetcode上该题名为minimum window substring
由两个字符串string1与string2,找出string1的一个子串,该子串包含了string2中所有的字符。最后返回这些子串中最短的一个。
例:
string1: this is a test string
string2: tist
输出: t stri (test string)
方法1(暴力搜索)
a)生成string1的所有子串
b)对每个子串检查是否包含了string2
c)返回最小的子串
方法2
1) 为string2建立一个数组count[].数组中存放字符出现的次数
stri中各个字符出现的次数为
count[‘i’] = 1
count[‘t’] = 2
count[’s’] = 1
2) 从左向右扫描string1,直到找到所有string2中的字符。为了检查是否找到所有字符,需要使用 1)中建立的count[]数组.因此首先找到“this is a t”子串,这个子串包含string2中的所有字符。然后更新所找到的结果。
3) 接着继续访问下一个字符,并将下一个字符添加到“this is a t”子串中。当新添加一个字符时,要检查新字符是否匹配子串左左边的字符(窗口左边界),如果匹配,将该字符添加到子串最右侧,并删除最左侧字符及该字符右侧所有多余的字符。当删除完这些字符后,计算新窗口的长度,并更新最小值。
注:要得到最小窗口,窗口最边界字符必然是目标字符中的字符,为了更新窗口,即向右移动左边界,只有当找到一个与左边界相等的字符才移动,这样能保证新窗口包含所有字符。而多余字符指未出现在目标串,以及重复出现的字符。 同理右边届扩展就等价于先将左边界向右移动,直到遇到在目标串中出现的字符,那么新的左边界就确定了,然后扩展右边界找出新窗口即可。
例:添加e到this is a t后,然后添加s,t. t匹配子串中左边界,因此将多余字符删除,并得到新的窗口t stri。随后更新最小值。最后加入n,g,这并未导致更新发生因此最小窗口中的字符是t stri。
4) 返回最小值。
原文地址:http://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/
leetcode上该题名为minimum window substring
由两个字符串string1与string2,找出string1的一个子串,该子串包含了string2中所有的字符。最后返回这些子串中最短的一个。
例:
string1: this is a test string
string2: tist
输出: t stri (test string)
方法1(暴力搜索)
a)生成string1的所有子串
b)对每个子串检查是否包含了string2
c)返回最小的子串
方法2
1) 为string2建立一个数组count[].数组中存放字符出现的次数
stri中各个字符出现的次数为
count[‘i’] = 1
count[‘t’] = 2
count[’s’] = 1
2) 从左向右扫描string1,直到找到所有string2中的字符。为了检查是否找到所有字符,需要使用 1)中建立的count[]数组.因此首先找到“this is a t”子串,这个子串包含string2中的所有字符。然后更新所找到的结果。
3) 接着继续访问下一个字符,并将下一个字符添加到“this is a t”子串中。当新添加一个字符时,要检查新字符是否匹配子串左左边的字符(窗口左边界),如果匹配,将该字符添加到子串最右侧,并删除最左侧字符及该字符右侧所有多余的字符。当删除完这些字符后,计算新窗口的长度,并更新最小值。
注:要得到最小窗口,窗口最边界字符必然是目标字符中的字符,为了更新窗口,即向右移动左边界,只有当找到一个与左边界相等的字符才移动,这样能保证新窗口包含所有字符。而多余字符指未出现在目标串,以及重复出现的字符。 同理右边届扩展就等价于先将左边界向右移动,直到遇到在目标串中出现的字符,那么新的左边界就确定了,然后扩展右边界找出新窗口即可。
例:添加e到this is a t后,然后添加s,t. t匹配子串中左边界,因此将多余字符删除,并得到新的窗口t stri。随后更新最小值。最后加入n,g,这并未导致更新发生因此最小窗口中的字符是t stri。
4) 返回最小值。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode刷题,没想到这么难搞!
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解