leetcode 3 Longest Substring Without Repeating Characters最长无重复子串
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without
repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
这个应该是一个典型的动态规划问题:http://bbs.csdn.net/topics/310174805
直观地得到一个思路,表达起来真够难的,直接写代码要更容易
以abcbef这个串为例
用一个数据结构pos记录每个元素曾出现的下标,初始为-1
从s[0]开始,pos['a'] == -1,说明a还未出现过,令pos['a'] = 0,视为将a"加入当前串",同时长度++
同理令pos['b'] = 1,pos['c'] = 2
到s[3]时,pos['b'] != -1,说明'b'在前面已经出现过了,此时可得到一个不重复串"abc",刷新当前的最大长度,然后做如下处理:
pos[s[0~2]] = -1,亦即将"ab""移出当前串",同时当前长度减去3
重复以上过程
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
/**
* Solution (DP, O(n)):
*
* Assume L[i] = s[m...i], denotes the longest substring without repeating
* characters that ends up at s[i], and we keep a hashmap for every
* characters between m ... i, while storing <character, index> in the
* hashmap.
* We know that each character will appear only once.
* Then to find s[i+1]:
* 1) if s[i+1] does not appear in hashmap
* we can just add s[i+1] to hash map. and L[i+1] = s[m...i+1]
* 2) if s[i+1] exists in hashmap, and the hashmap value (the index) is k
* let m = max(m, k), then L[i+1] = s[m...i+1], we also need to update
* entry in hashmap to mark the latest occurency of s[i+1].
*
* Since we scan the string for only once, and the 'm' will also move from
* beginning to end for at most once. Overall complexity is O(n).
*
* If characters are all in ASCII, we could use array to mimic hashmap.
*/
int lengthOfLongestSubstring(string s) {
// for ASCII char sequence, use this as a hashmap
vector<int> charIndex(256, -1);
int longest = 0, m = 0;
for (int i = 0; i < s.length(); i++) {
m = max(charIndex[s[i]] + 1, m); // automatically takes care of -1 case
charIndex[s[i]] = i;
longest = max(longest, i - m + 1);
}
return longest;
}
下面给出python代码:
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
start = maxLength = 0
usedChar = {} for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]:
start = usedChar[s[i]] + 1
else:
maxLength = max(maxLength, i - start + 1) usedChar[s[i]] = i return maxLength
下面是c语言的版本:
// testlongsetString.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <stdio.h>
#include<iostream> using namespace std; void GetMaxUnRepeatSubStr(char *str)
{
//global var
int hashTable[256] ={0};
char* pMS = str;
int mLen = 0; //temp var
char* pStart = pMS;
int len = mLen;
char* p = pStart;
while(*p != '\0')
{
if(hashTable[*p] == 1)
{
if(len > mLen)
{
pMS = pStart;
mLen = len;
} while(*pStart != *p)
{
hashTable[*pStart] = 0;
pStart++;
len--;
}
pStart++;
}
else
{
hashTable[*p] = 1;
len++;
}
p++;
}
// check the last time
if(len > mLen)
{
pMS = pStart;
mLen = len;
}
//print the longest substring
while(mLen>0)
{
cout<<*pMS<<" ";
mLen--;
pMS++;
}
cout<<endl;
} int main()
{
char* str1="bdabcdcf";
GetMaxUnRepeatSubStr(str1);
char* str2="abcdefb";
GetMaxUnRepeatSubStr(str2);
char* str3="abcbef";
GetMaxUnRepeatSubStr(str3); return 0;
}
参考文献:
leetcode 3 Longest Substring Without Repeating Characters最长无重复子串的更多相关文章
- [LeetCode] 3.Longest Substring Without Repeating Characters 最长无重复子串
Given a string, find the length of the longest substring without repeating characters. Example 1: In ...
- [LeetCode] Longest Substring Without Repeating Characters 最长无重复子串
Given a string, find the length of the longest substring without repeating characters. For example, ...
- 【LeetCode】3.Longest Substring Without Repeating Characters 最长无重复子串
题目: Given a string, find the length of the longest substring without repeating characters. Examples: ...
- [LeetCode] Longest Substring Without Repeating Characters最长无重复子串
Given a string, find the length of the longest substring without repeating characters. For example, ...
- [LeetCode] Longest Substring Without Repeating Characters 最长无重复字符的子串
Given a string, find the length of the longest substring without repeating characters. Example 1: In ...
- [LeetCode] Longest Substring Without Repeating Characters 最长无重复字符的子串 C++实现java实现
最长无重复字符的子串 Given a string, find the length of the longest substring without repeating characters. Ex ...
- 【LeetCode每天一题】Longest Substring Without Repeating Characters(最长无重复的字串)
Given a string, find the length of the longest substring without repeating characters. Example 1: ...
- LeetCode Longest Substring Without Repeating Characters 最长不重复子串
题意:给一字符串,求一个子串的长度,该子串满足所有字符都不重复.字符可能包含标点之类的,不仅仅是字母.按ASCII码算,就有2^8=128个. 思路:从左到右扫每个字符,判断该字符距离上一次出现的距离 ...
- 003 Longest Substring Without Repeating Characters 最长不重复子串
Given a string, find the length of the longest substring without repeating characters.Examples:Given ...
随机推荐
- 【USACO15FEB】审查(黄金)Censoring (Gold)
题目描述 Farmer John has purchased a subscription to Good Hooveskeeping magazine for his cows, so they h ...
- BZOJ4943 [NOI2017] 蚯蚓
题目描述 蚯蚓幼儿园有nn 只蚯蚓.幼儿园园长神刀手为了管理方便,时常让这些蚯蚓们列队表演. 所有蚯蚓用从11 到nn 的连续正整数编号.每只蚯蚓的长度可以用一个正整数表示,根据入园要求,所有蚯蚓的长 ...
- SpringCloud学习之Zuul统一异常处理及回退
一.Filter中统一异常处理 其实在SpringCloud的Edgware SR2版本中对于ZuulFilter中的错误有统一的处理,但是在实际开发当中对于错误的响应方式,我想每个团队都有自己的处理 ...
- Java中的String,StringBuilder,StringBuffer三者的区别
最近在学习Java的时候,遇到了这样一个问题,就是String,StringBuilder以及StringBuffer这三个类之间有什么区别呢,自己从网上搜索了一些资料,有所了解了之后在这里整理一下, ...
- 如何用cmd通过sublime打开文件?
sublime 提供了专门的命令工具subl.exe,就在它的安装目录之下,讲安装目录配置到系统环境变量中就OK了.具体如下: 1.找到sublime安装路径 如我的默认路径:C:\Program F ...
- 【ASP.NET Core】给中间件传参数的方法
最近博客更新频率慢了些,原因有三: 其一,最近老周每星期六都录 ASP.NET Core 的直播,有些内容在视频里讲过,就不太想在博客里面重复.有兴趣的话可以去老周的微博看,或者去一直播,直播帐号与微 ...
- joomla网站内插入doc文档
最近我的网站又出了问题,之前用joomla做的网站,由于要放doc文档,后来想尽办法终于用iframe的办法,先把文档传到scribd网,然后把文档嵌到网站里去,但是狗血的,去年五月份的时候我们伟大的 ...
- 用go实现常用算法与数据结构——队列(queue)
queue 简介 队列是一种非常常见的数据结构,日常生活中也能经常看到.一个典型的队列如下图(图片来自 segmentfault): 可以看出队列和我们日常生活中排队是基本一致的.都遵循 FIFO(F ...
- Windows下的DOM操作
前言:这学期学Linux之后,发现用命令行的方式来操作电脑还是很好玩的~写这篇随笔来总结下Windows环境下通过DOS来执行命令的操作,希望能帮到您~自己忘记的时候能回来复习emmm 启动DOS环境 ...
- Redis从入门到精通:中级篇
原文链接:http://www.cnblogs.com/xrq730/p/8944539.html,转载请注明出处,谢谢 本文目录 上一篇文章以认识Redis为主,写了Redis系列的第一篇,现在开启 ...