lintcode刷题——最长无重复字符的子串
来源:互联网 发布:网络外部性 编辑:程序博客网 时间:2024/05/16 08:41
原题如下:
最长无重复字符的子串
给定一个字符串,请找出其中无重复字符的最长子字符串。
例如,在"abcabcbb"
中,其无重复字符的最长子字符串是"abc"
,其长度为 3
。
对于,"bbbbb"
,其无重复字符的最长子字符串为"b"
,长度为1
。
1、首先想到的办法就是,双层循环来做,遍历每一个字符,从该字符开始往后的字符计数,直到遇到重复的字符停止,该方法复杂度较高;
2、改进方法:使用两个函数,写一个计算字符串的最长前缀子串的函数,再用一层循环进行遍历,从当前字符直到末尾求其最长前缀子串的值,最大的即为所求的无重复字符的最长子字符串。
具体的c++代码如下:
int lengthOfLongestSubstring(string s) {
// write your code here
int l = s.size();
if (l == 0)
{
return 0;
}
int i, j;
int res = 0;
for (i = 0; i<l; i++)
{
int hash[200];
memset(hash, 0, sizeof(hash));
hash[s[i]]++;
for (j = i + 1; j<l; j++)
{
if (hash[s[j]] == 0)
{
hash[s[j]]++;
}
else
{
break;
}
}
if (j - i>res)
{
res = j - i;
}
}
return res;
}//双层循环做法
用最长前缀字符串来求:
int maxbefore(const string &s)//最长无重复前缀子串长度
{
int hash[200];
int i = 0;
int count = 0;
memset(hash, 0, sizeof(hash));
while (i<s.size()&&!hash[s[i]])
{
hash[s[i]]++;
i++;
count++;
}
return count;
}
int lengthOfLongestSubstring(string &s)
{
int l = s.size();
int i;
int res = 0;
for (i = 0; i < l; i++)
{
if (maxbefore(s.substr(i))>res)
{
res = maxbefore(s.substr(i));
}
}
return res;
}
- lintcode刷题——最长无重复字符的子串
- LintCode-最长无重复字符的子串
- LintCode-最长无重复字符的子串
- LintCode:最长无重复字符的子串
- 最长无重复字符的子串 lintcode
- lintcode,最长无重复字符的子串
- lintcode(384)最长无重复字符的子串
- lintcode--最长无重复字符的子串
- [LintCode]384.最长无重复字符的子串
- LintCode:M-最长无重复字符的子串
- [LintCode 384] 最长无重复字符的子串(Python)
- lintcode最长无重复字符的子串
- LintCode 最长无重复字符的子串
- 最长无重复字符的子串-LintCode
- 最长无重复字符的子串
- 最长无重复字符的子串
- 最长无重复字符的子串
- 最长无重复字符的子串
- easyui-validatebox 验证
- LeetCode-Add Two Numbers
- 什么是重构,什么不是重构
- Git常用命令
- 前端框架 jQuery EasyUI(一)源码包、两种方式声明表格控件
- lintcode刷题——最长无重复字符的子串
- Angular 小试牛刀[1]-Getting Started
- redis必杀高级:数据备份与恢复
- NYOJ 171 聪明的kk
- window7 x64 安装docker-toolbox
- Java技术常用设计模式(二)--- 代理模式
- hdu 2084 数塔 动态规划 简单
- 常见的一个错误音频混音算法
- IO模型