LeetCode340 Longest Substring with At Most K Distinct Characters
2016-04-15 15:37
309 查看
This is a question needs pay for , I have no money to pay ,so just write some test case by myself.
If you read this blog , and you hava pay for the LeetCode ,and you have test my program , please tell me that wheather is works, thank you.
This idea is:We use double pointer and a count , and an array calls "locs" to save the char last occur position.
if cnt>k,we need find the minimum position that a char occur. Here we can also use a map do this.
If you think why I use so ugly Englist to write this blog .Well ,Beacuse my computer is so slow if I use the Pinyin.Fuck the computer ,Fuck the Sougou.
Then , My Code:
If you read this blog , and you hava pay for the LeetCode ,and you have test my program , please tell me that wheather is works, thank you.
This idea is:We use double pointer and a count , and an array calls "locs" to save the char last occur position.
if cnt>k,we need find the minimum position that a char occur. Here we can also use a map do this.
If you think why I use so ugly Englist to write this blog .Well ,Beacuse my computer is so slow if I use the Pinyin.Fuck the computer ,Fuck the Sougou.
Then , My Code:
#include <stdio.h> #include <string.h> #include <string> using namespace std; int getSub(string a,int k){ int n = a.size(); if(k>=n) return n; int cntChar = 0; int len = 0; int start = 0; int newStart=0; int locs[256]; memset(locs,-1,sizeof(locs)); for(int i=0;i<n;i++){ newStart = start; if(locs[a[i]] == -1){cntChar++;} locs[a[i]] = i; if(cntChar<=k){len = max(len,i-start+1);} else{ for(int j=start+1;j<locs[a[start]];j++){ newStart = min(locs[a[start]],locs[a[j]]); } locs[a[newStart]] = -1; cntChar --; start = newStart+1; len = max(len,i-start+1); } } return len; } int main() { string a = "ecebbbbbcecba"; int k = 2; int res = getSub(a,k); printf("%d\n",res); system("pause"); return 0; }
相关文章推荐
- R 学习 -- factor
- 两个界面的翻转
- JVM性能调优
- Linux内核学习笔记六——并发和同步概念
- ICPCCamp 2016 Day3 - G Random Arighmetic (dp)
- SQL查询相关技术-7.SQL操作(形成2个数据表)
- R 学习 -- vector
- OA项目实战学习(8)——配置权限的树形结构显示
- 【Wireless】通过WE扩展获取当前信道
- JSPatch使用
- MFC VC++多线程间通信
- 二叉平衡查找树:
- 调用http://apistore.baidu.com网站的接口
- IntelliJ IDEA 2016.1(64) 注册码
- NSInvalidArgumentException’, reason: ‘data parameter is nil
- HTML5新特性之WebSocket
- SQL查询中in、exists、not in、not exists的用法与区别
- Java Oracle数据库连接
- 虚拟内存与物理内存
- 各种浏览器的内核是什么