leetcode解题笔记-Minimum Window Substring
来源:互联网 发布:骑马与砍杀哈劳斯数据 编辑:程序博客网 时间:2024/05/20 19:33
原题地址:https://oj.leetcode.com/problems/minimum-window-substring/
题目要求从一个字符串S中找到包含字符串T的最小字串
刚拿到这题,我想到有几个点要解决:
1.如何记录用什么来记录是否包含字符串T
2.怎样记录是否是最小的子串
原来想的是用栈,不过不太行。
后来实在想不到方案,去看了一下提示,主要提示为Hash Table,Two Pointers
看这个意思,hash table用来记录是否包含字符串,Two Pointers应该是用于控制最小子串
这个问题想的时间花得有点多,所以看了网上的答案,这个http://blog.csdn.net/doc_sgl/article/details/12395759
首先用hashmap记录T中的字符以及出现的次数,needToFind。再用一个hashmap记录S表示查到的字符,及次数,hasFind
当hasFind的数量大于等于needToFind的数量的时候,可以移动窗口(窗口初始为0到i(迭代的次数))。
满足以下条件时,移动start,当S在start所在的字符串在hasFind大于needToFind时可移动,或者当S在start所在的字符串不再hasFind时也移动。在移动的过程中,记录最小字串。代码如下
class Solution: # @return a string def minWindow(self, S, T): needToFind = {} hasFind = {} for c in T: needToFind[c] = 1 if not needToFind.has_key(c) else needToFind[c]+1 count,start = 0,0 minLength = None minStart = None for i in range(0,len(S)): if not needToFind.has_key(S[i]): continue hasFind[S[i]] = 1 if not hasFind.has_key(S[i]) else hasFind[S[i]]+1 if hasFind[S[i]] <= needToFind[S[i]]: count += 1 if count == len(T): while True: if not needToFind.has_key(S[start]): start+=1 continue elif hasFind[S[start]]>needToFind[S[start]]: hasFind[S[start]] -= 1 start+=1 else: break if not minLength or i - start + 1 < minLength: minStart = start minLength = i-start + 1 if minLength == None: return "" return S[minStart:minStart+minLength]print Solution().minWindow("cabwefgewcwaefgcf", "cae")
0 0
- leetcode解题笔记-Minimum Window Substring
- [LeetCode] Minimum Window Substring 解题报告
- [leetcode] 76. Minimum Window Substring 解题报告
- [Leetcode] 76. Minimum Window Substring 解题报告
- LeetCode: Minimum Window Substring
- LeetCode Minimum Window Substring
- LeetCode : Minimum Window Substring
- [LeetCode] Minimum Window Substring
- [Leetcode] Minimum Window Substring
- LeetCode: Minimum Window Substring
- [LeetCode]Minimum Window Substring
- [leetcode]Minimum Window Substring
- Leetcode:Minimum Window Substring
- LeetCode-Minimum Window Substring
- [leetcode] Minimum Window Substring
- [leetcode] Minimum Window Substring
- leetcode Minimum Window Substring
- [LeetCode] Minimum Window Substring
- Windows环境下搭建基于CooCox CoIDE的STM32 GCC 开发环境
- 在ARC下 选择使用weak和assign的区别
- Apache ActiveMQ 持久化到MySQL数据库的简单配置
- POJ1860 - Currency Exchange
- 外设与存储器交互方式总结
- leetcode解题笔记-Minimum Window Substring
- 解决500 OOPS: vsftpd: cannot locate user specified in 'ftp_username':ftp的问题
- Java SE 第十讲(面向对象之封装) 续
- 读书笔记——程序员成长的烦恼(吴亮等)
- Eclipse调试Hbase程序“Failed to detect a valid hadoop home directory java.id.IOException”问题
- 再探Objective-C.4
- HDU3639 Hawk-and-Chicken 强连通+缩点+建反向图
- 解决linux 下php中xdebug的报错 :Xdebug MUST be loaded as a Zend extension in Unknown on line 0
- 编译内核使用make menuconfig时出错, 是一个目录 停止