Leetcode-Minimum Window Substrings(unordered_map)
来源:互联网 发布:单例模式 java 双重锁 编辑:程序博客网 时间:2024/06/05 18:05
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 empty string""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
算法思想:通过建立hash表unordered_map来记录扫描过的元素,并且记录其重复个数。因为S只能遍历一遍,所以还需要两个指针去限制最终包含区域的范围,即first与behind。且还需要一个count去记录每次循环过程中是否达到了包含字符串T的条件。具体代码如下:
string minWindow(string S, string T) {string result;if (S.empty() || T.empty())return result;unordered_map<char, int> m1; //建立<char,int>类型的hash表,方便记录重复元素unordered_map<char, int> m2;for (int i = 0; i < T.length(); i++)m1[T[i]]++; //记录target中每个元素的个数int first = 0, behind = 0;//用两个指针去维护字符串Sint count=0;//监控器int minlength = INT_MAX;for (; first < S.length(); first++) {if (m1.find(S[first]) != m1.end()) {m2[S[first]]++;if (m2[S[first]] <= m1[S[first]]) // 元素重复不能比待匹配串多count++;}if (count >= T.length()) {while (m1.find(S[behind]) == m1.end() || m2[S[behind]]>m1[S[behind]]) { //当出现查找不到或者m2的某元素已经多余m1的这个元素时m2[behind]--;behind++; //向后移一位}if (first - behind + 1 < minlength) { //遇到更短的区间时更新minlength = first - behind + 1;result = S.substr(behind, minlength);}}}return result;}
阅读全文
0 0
- Leetcode-Minimum Window Substrings(unordered_map)
- 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
- [LeetCode] Minimum Window Substring
- leetcode minimum window substring
- LeetCode - Minimum Window Substring
- 使用getopt_long()从命令行获取参数,struct option
- 选择器的优先级问题
- 一个自定义的折线图
- AppStore搜索框内容设置以及点击Search
- 如何选择机器学习的算法
- Leetcode-Minimum Window Substrings(unordered_map)
- 培训作业:泛型和集合
- HNOI-2015 菜肴制作
- 递归函数
- python绘制神经网络中的ReLU激活函数图像(附代码)
- 1049. Counting Ones (30)
- 学PPT时的作品
- Centos 7上安装WordPress
- JAVA垃圾回收机制