Lintcode 最小子串覆盖
来源:互联网 发布:java singleton模式 编辑:程序博客网 时间:2024/05/19 16:47
给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的子串。
说明
在答案的子串中的字母在目标字符串中是否需要具有相同的顺序?
——不需要。
样例
思路:给出source = "ADOBECODEBANC",target = "ABC" 满足要求的解 "BANC"
该题使用的是Hash表的方法。
首先创建两个映射 map1(Key,Value),map2(Key,Value),其中Key代表两个string类型字符串中字母,先将 Target 中的字母映射到 map 中,然后再对 source 做一个循环,通过比较map1 和map2 中的Value 的大小来确定是否找到Target 中的值,若找到将变量 found++,当 found == Target. size()时说明已经找到子串的一个覆盖,确定初始位置 start 和结尾 end 后计算覆盖长度。将start 后移一位继续寻找下一个覆盖,最终得到最小覆盖。
代码如下:
class Solution {public: /** * @param source: A string * @param target: A string * @return: A string denote the minimum window * Return "" if there is no such a string */ string minWindow(string &source, string &target) { // write your code here string result; int n=source.size(); int m=target.size(); int start=-1,flag=m,min=n+1,first=-1; vector<int> t(256,0),s(256,0); if(target.empty()||source.empty()) return ""; for(int i=0;i<m;i++){ t[target[i]]++; } for(int i=0;i<n;i++){// cout<<(int)s['d']<<" "<<(int)s['b']<<" "<<min<<" "<<flag<<" "<<first<<endl; if(t[source[i]]>s[source[i]]){ s[source[i]]++; flag--; } else s[source[i]]++; if(flag==0){ start++; while(t[source[start]]==0||(t[source[start]]!=0&&t[source[start]]<=s[source[start]]-1)){ if(t[source[start]]<=s[source[start]]-1) s[source[start]]--; start++; } if(min>i-start+1){ min=i-start+1; first=start; } flag++; s[source[start]]--; } } if(min==n+1) return ""; else return source.substr(first,min); }};
0 0
- LintCode:最小子串覆盖
- Lintcode 最小子串覆盖
- lintcode--最小子串覆盖
- lintcode-最小子串覆盖-32
- LintCode 32 最小子串覆盖
- lintcode(32)最小子串覆盖
- LintCode:M-最小子串覆盖
- 最小覆盖子串
- 最小子串覆盖
- 最小覆盖子串
- 最小子串覆盖
- 最小子串覆盖
- 最小子串覆盖
- 最小子串覆盖
- 最小覆盖子串 KMP
- 【t011】最小覆盖子串
- LintCode--最小子数组
- lintcode ----最小子数组
- virtualenvs error: deactivate must be sourced. Run 'source deactivate' instead of 'deactivate'
- 安卓打包出现问题
- QT之GUI学习笔记(八)----菜单和工具条的优化
- .dat文件三维点云可视化
- java se 01
- Lintcode 最小子串覆盖
- Android中去掉EditText的下划线
- PCL常用语句
- office技巧(一)——excel如何流畅输入
- Linux系统入门学习:教你在VirtualBox 安装 Ubuntu 15.04
- React项目的打包与部署到腾讯云
- eclipse配置tomcat8.5报错The Apache Tomcat installation at this directory is version 8.5.4. A Tomcat 8.0
- 【职业生涯】6年开发,打算从技术转产品
- 【每天一点linux】说说linux权限管理那点儿事