longest substring without repeat characters(leetcode3,lintcode384)

Given a string, find the length of the **longest substring **without repeating characters.
Examples:
Given"abcabcbb", the answer is"abc", which the length is 3.
Given"bbbbb", the answer is"b", with the length of 1.
Given"pwwkew", the answer is"wke", with the length of 3. Note that the answer must be a substring,"pwke"is a subsequence and not a substring.
Subscribe to see which companies asked this question.
题目描述如上。
一开始的想法就是维护start,end分别表示substring with non-repeating characters的起始和结束。但是如何更新以及在什么时候更新这两个变量,没有弄清楚。匆忙写了代码,提交,自然是wrong answer。看了discuss之后,仿照java版的答案,写了C++的版本。
代码如下。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int maxlen = 0;
        map dict;
        for(int i=0,j=0 ; i

1.需要注意每次更新j时,都需要将j同dict[s[i]]+1进行比较,选择两者中的较大数,如果仅将j更新成dict[s[i]]+1,而没有进行比较,就不能处理如abcba的情形。

你可能感兴趣的:(longest substring without repeat characters(leetcode3,lintcode384))