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. ●2301 [HAOI2011] Problem b

    题链: http://www.lydsy.com/JudgeOnline/problem.php?id=2301 题解: 莫比乌斯反演,入门题. 类似●HDU 1695 GCD 只是多了一个下界,(另 ...

  2. poj 2425 AChessGame(博弈)

    A Chess Game Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 3791   Accepted: 1549 Desc ...

  3. [BZOJ]1023 cactus仙人掌图(SHOI2008)

    NOIP后的第一次更新嗯. Description 如果某个无向连通图的任意一条边至多只出现在一条简单回路(simple cycle)里,我们就称这张图为仙人掌图(cactus).所谓简单回路就是指在 ...

  4. [usaco6.1.1Postal Vans]

    来自FallDream的博客,未经允许,请勿转载,谢谢. 给你一个4*n的棋盘,问从(1,1)出发恰好经过所有格子一次的走法数量.(n<=1000) 插头dp,用f[i][j][k]表示转移到第 ...

  5. bzoj4665小w的喜糖 dp+容斥

    4665: 小w的喜糖 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 120  Solved: 72[Submit][Status][Discuss] ...

  6. Unix文件系统的主要特点是什么?

    1.  树型层次结构 2.  可安装拆卸的文件系统 3.  文件是无结构的字符流式文件 4.  Unix文件系统吧外部设备和文件目录作为文件处理

  7. 笔记10 在XML中声明切面(1)

    1.无注解的Audience package XMLconcert; public class Audience { public void silenceCellPhones() { System. ...

  8. mvn package 和 mvn install

    刚刚准备将maven项目中一个子项目打个包,使用了mvn package.心想这个很简单嘛,没料就报错了.报错咱不怕,看看错在哪就好了. 编译出错,找不到我定义的异常类中的配置.那应该是引用父模块出来 ...

  9. sqlserver 截取字符串(转)

    SQL Server 中截取字符串常用的函数: 1.LEFT ( character_expression , integer_expression ) 函数说明:LEFT ( '源字符串' , '要 ...

  10. Oracle知识梳理(一)理论篇:基本概念和术语整理

    理论篇:基本概念和术语整理 一.关系数据库           关系数据库是目前应用最为广泛的数据库系统,它采用关系数据模型作为数据的组织方式,关系数据模型由关系的数据结构,关系的操作集合和关系的完整 ...