[leetcode] 76.Minimum Window Substring
来源:互联网 发布:彩色macd指标源码 编辑:程序博客网 时间:2024/05/20 19:29
题目:
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”.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
题意:
给定一个字符串S和一个字符串T。找出S中最小的窗口包含了S中所有的字符。
思路:
首先我们需要记录T中的字符,因为每个字符可能出现多次,所以我们需要记录该字符对应的个数。不妨使用256位的数组当做哈希表。统计T中每个字符出现的次数。然后,我们使用两个指针,初始化时第一个指针指向了S中的第一个元素,然后让第二个指针从第一个指针的位置开始往后扫描,直到找到能够了T中所有的字符,然后往后移动第一个指针来缩小这个窗口,截止条件是不能满足T中所有的字符出现的次数。此时继续往后移动第二个指针。一直到第二个指针移动到字符串末尾。
以上。
代码如下:
class Solution {public: string minWindow(string s, string t) { if (s.empty() || t.empty())return ""; int first = 0, second = 0; int table[256]; for (int i = 0; i < 256; i++)table[i] = INT_MIN; int un_meets = 0; for (auto c : t) { if (table[c] == INT_MIN) { table[c] = 1; un_meets++; } else table[c]++; } int sLen = s.length(); int tLen = t.length(); int shortest = INT_MAX; string result = ""; while (first < sLen && table[s[first]] == INT_MIN)first++; second = first; while (second < sLen) { if (table[s[second]] != INT_MIN) { table[s[second]]--; if (table[s[second]] == 0)un_meets--; while (un_meets == 0) { if (table[s[first]] != INT_MIN && second - first + 1 < shortest) { shortest = second - first + 1; result = s.substr(first, shortest); if (shortest == tLen)return result; } if (table[s[first]] != INT_MIN) { table[s[first]]++; if (table[s[first]] == 1)un_meets++; } first++; } } second++; } return result; }};
0 0
- LeetCode 76. Minimum Window Substring
- [LeetCode]76.Minimum Window Substring
- LeetCode 76.Minimum Window Substring
- LeetCode --- 76. Minimum Window Substring
- [Leetcode] 76. Minimum Window Substring
- [leetcode] 76.Minimum Window Substring
- **LeetCode 76. Minimum Window Substring
- leetcode 76. Minimum Window Substring
- 【LeetCode】76. Minimum Window Substring
- LeetCode 76. Minimum Window Substring
- Leetcode 76. Minimum Window Substring
- leetcode.76. Minimum Window Substring
- LeetCode 76. Minimum Window Substring
- [LeetCode] 76. Minimum Window Substring
- leetcode 76.Minimum Window Substring
- leetcode 76. Minimum Window Substring
- 76. Minimum Window Substring, leetcode
- leetcode-76. Minimum Window Substring
- Python使用requests库模拟登陆网站的方式--以豆瓣为例
- mysql创建外键(Foreign Key)方法
- VelocityTracker简介
- android判断手机是否连网
- 通过反射访问任意类的私有方法和属性
- [leetcode] 76.Minimum Window Substring
- Qt中设置桌面应用程序图标
- Tez控制输出的文件是否压缩并指定文件名
- LeetCode OJ 之 Add Digits (数字相加)
- MyBatis学习笔记(六)动态sql
- IMPDP 时遇 ORA-31623、ORA-06512 错误解决一例
- 关于安卓 Couldn't load memtrack module (No such file or directory) 的错误
- Oracle删除用户
- Android关闭或打开软键盘