leetcode 3 Longest Substring Without Repeating Characters最长无重复子串

时间:2022-10-19 23:01:10

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. &lbrack;LeetCode&rsqb; 3&period;Longest Substring Without Repeating Characters 最长无重复子串

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

  2. &lbrack;LeetCode&rsqb; Longest Substring Without Repeating Characters 最长无重复子串

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

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

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

  4. &lbrack;LeetCode&rsqb; Longest Substring Without Repeating Characters最长无重复子串

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

  5. &lbrack;LeetCode&rsqb; Longest Substring Without Repeating Characters 最长无重复字符的子串

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

  6. &lbrack;LeetCode&rsqb; Longest Substring Without Repeating Characters 最长无重复字符的子串 C&plus;&plus;实现java实现

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

  7. 【LeetCode每天一题】Longest Substring Without Repeating Characters&lpar;最长无重复的字串&rpar;

    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. 如何在Visual Studio 工程之间共享静态内容 &lpar;js&comma; css&comma; img&comma; etc&period;&rpar;

     第一步: 文件夹上点击右键 -> Add -> Existing Item,单击选中文件,不要点击“Add”按钮,而是在“Add”按钮右边有个向下的小箭头,点击这个箭头,再点击“Add ...

  2. Excel函数——DATE、SUBSTITUTE、REPLACE、ISERROR、IFERROR

    1.DATE DATE 函数返回表示特定日期的连续序列号.例如,公式 =DATE(2008,7,8) 返回 2008-7-8或39637,取决于单元格格式,但空单元格计算和默认为日期格式. DATE也 ...

  3. apache配置多个虚拟主机

    设置apache 多个虚拟目录记录 #配置第2个虚拟目录<VirtualHost 127.0.0.2:80>ServerName www.xx.comDocumentRoot " ...

  4. &lbrack;iOS基础控件 - 7&period;0&rsqb; UIWebView

    A.基本使用 1.概念 iOS内置的浏览器控件 Safari浏览器就是通过UIWebView实现的   2.用途:制作简易浏览器 (1)基本请求 创建请求 加载请求 (2)代理监听webView加载, ...

  5. &lbrack;SinGuLaRiTy&rsqb; COCI 2016~2017 &num;5

    [SinGuLaRiTy-1012] Copyright (c) SinGuLaRiTy 2017. All Rights Reserved. 最近神犇喜欢考COCI...... 测试题目 对于所有的 ...

  6. 从JavaWeb危险字符过滤浅谈ESAPI使用

    事先声明:只是浅谈,我也之用了这个组件的一点点. 又到某重要XX时期(但愿此文给面临此需求的同仁有所帮助),某Web应用第一次面临安全加固要求,AppScan的安全测试报告还是很清爽的,内容全面,提示 ...

  7. 古典音乐 (java基础 继承)

    摘要: 原创出处: http://www.cnblogs.com/Alandre/ 泥沙砖瓦浆木匠 希望转载,保留摘要,谢谢! 一.前言 小朽不才,最近爱上了听古典音乐收录了,mozart ,贝多芬… ...

  8. cocos2dx内存管理

    cocos2dx基于引用计数管理内存,所有继承自CCObject的对象都将获得引用计数的能力,可通过调用retain成员函数用于引用计数值,调用release减少引用计数值,当计数值减为0时销毁对象. ...

  9. ubuntu upgrade

    升级命令 虽然 apt-get 经常被人诟病,但实际上它还是个挺好用的软件包管理器.在 Ubuntu 14.04 以后的系统中,apt-get 相关的升级更新命令有四个: apt-get update ...

  10. POJ 1087

    #include<iostream> #include<stdio.h> #include<string> #define MAXN 105 using names ...