[LeetCode]longest substring without repeating characters

问题描述

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 subsequenceand not a substring.

解题思路

用一个map记录各个字符的下标,首先将所有的下表初始化为-1,然后向后遍历的过程中记录当前字符的下标,并将当前字符的下标与上一个相同字符的下标做差值,即可得到它们之间无重复字符的子串。然后用Max记录更新最大子串数,并更新map存储的下标值,即从这个重复值重新开始数字符串的数(最大无重复字符子串必定在两个重复字符之间,或者是整个字符串的长度)

代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char,int> book;
        int i,Max=0,pre=-1;
        for(i=0;i<s.length();i++) book[s[i]]=-1;
        for(i=0;i<s.length();i++)
        {
            pre=max(pre,book[s[i]]);//更新map中各个字符的下标
            Max=max(Max,i-pre); //保存暂时的最大无重复子串长度
            book[s[i]]=i; //计算差值后继续更新
        }
        return Max;
    }
};

猜你喜欢

转载自blog.csdn.net/lvquanye9483/article/details/81636115