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最长无重复子串的更多相关文章

  1. [LeetCode] 3.Longest Substring Without Repeating Characters 最长无重复子串

    Given a string, find the length of the longest substring without repeating characters. Example 1: In ...

  2. [LeetCode] Longest Substring Without Repeating Characters 最长无重复子串

    Given a string, find the length of the longest substring without repeating characters. For example, ...

  3. 【LeetCode】3.Longest Substring Without Repeating Characters 最长无重复子串

    题目: Given a string, find the length of the longest substring without repeating characters. Examples: ...

  4. [LeetCode] Longest Substring Without Repeating Characters最长无重复子串

    Given a string, find the length of the longest substring without repeating characters. For example, ...

  5. [LeetCode] Longest Substring Without Repeating Characters 最长无重复字符的子串

    Given a string, find the length of the longest substring without repeating characters. Example 1: In ...

  6. [LeetCode] Longest Substring Without Repeating Characters 最长无重复字符的子串 C++实现java实现

    最长无重复字符的子串 Given a string, find the length of the longest substring without repeating characters. Ex ...

  7. 【LeetCode每天一题】Longest Substring Without Repeating Characters(最长无重复的字串)

    Given a string, find the length of the longest substring without repeating characters. Example 1:    ...

  8. LeetCode Longest Substring Without Repeating Characters 最长不重复子串

    题意:给一字符串,求一个子串的长度,该子串满足所有字符都不重复.字符可能包含标点之类的,不仅仅是字母.按ASCII码算,就有2^8=128个. 思路:从左到右扫每个字符,判断该字符距离上一次出现的距离 ...

  9. 003 Longest Substring Without Repeating Characters 最长不重复子串

    Given a string, find the length of the longest substring without repeating characters.Examples:Given ...

随机推荐

  1. bzoj 1880: [Sdoi2009]Elaxia的路线

    Description 最近,Elaxia和w的关系特别好,他们很想整天在一起,但是大学的学习太紧张了,他们 必须合理地安排两个人在一起的时间.Elaxia和w每天都要奔波于宿舍和实验室之间,他们 希 ...

  2. bzoj2839: 集合计数 容斥+组合

    2839: 集合计数 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 523  Solved: 287[Submit][Status][Discuss] ...

  3. Linux input子系统 io控制字段【转】

    转自:http://www.cnblogs.com/leaven/archive/2011/02/12/1952793.html http://blog.csdn.net/guoshaobei/arc ...

  4. C++ C# python 中常用数学计算函数对比

    1.求x 的n次幂. C++ #include<cmath> f=pow(x,n) C# f=Math.Pow(x,n) python import numpy as np f=np.po ...

  5. 试说明采用双缓冲技术如何进行I/O操作

    输入设备先将第一个缓冲区装满数据,在输入设备向第二个缓冲区装数据时,处理机就可以从第一个缓冲区取出数据进行处理:当一个缓冲区的数据处理完毕,若第二个缓冲区已经装满,则处理机又可以从第二个缓冲区取出数据 ...

  6. C#+HtmlAgilityPack+Dapper走一波爬虫

    最近因为公司业务需要,又有机会撸winform了,这次的需求是因为公司有项目申报的这块业务,项目申报前期需要关注政府发布的相关动态信息,政府部门网站过多,人工需要一个一个网站去浏览和查阅,有时候还会遗 ...

  7. git日常使用经验积累

    1 git merge origin/develop 将远程分支合并到本地,一般先执行合并,解决冲突,然后再git commit合入新建的分支,推送到远程分支里面,最后码云上找pl pull requ ...

  8. c语言程序第2次作业

    (一)改错题 1.输出带框文字:在屏幕上输出以下3行信息. 错误信息1:{{uploading-image-560144.png(uploading...)} 错误原因:stdio误写为stido 错 ...

  9. 实验:利用ASMLib创建ASM磁盘

    环境:RHEL 6.5 + Oracle 11.2.0.4 RAC(2 nodes) 目的:在实验环境使用ASMLib配置共享ASM磁盘,虽然我们已经不建议使用ASMLib进行绑盘,但是无奈有客户是这 ...

  10. [Java] 设计模式:代码形状 - lambda表达式的一个应用

    [Java] 设计模式:代码形状 - lambda表达式的一个应用 Code Shape 模式 这里介绍一个模式:Code Shape.没听过,不要紧,我刚刚才起的名字. 作用 在应用程序的开发中,我 ...