LeetCode刷题笔记0122,Longest Substring Without Repeating Characters

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majalis_C/article/details/86597813

3. Longest Substring Without Repeating Characters

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

题目大意:给出一个字符串,计算其中最大的不重复子字符串的元素个数。

解决方式:

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;
    }

解释:

用一个集合来记录不重复的ASCII码,包含字符串可表示的所有元素的最大集。(ASCII有256个元素)

start记录左面遇到的第一个不在当前最大子串内的元素在字符串中的下标。

i为当前遍历的字符串中元素下标。

整体思路是,将当前访问的元素ASCII码值同其在字符串中的位置一一对应下来。如果在接下来的字符串元素访问中,出现了和之前元素相同的字符,则将其元素下标赋值给start。这样,用i-start+1得出的就是当前访问过的最大子字符串的元素个数。

此处利用ASCII码值作为index用法很巧妙。

表达能力有限,举个橘子

例如:abcabca

i=0;start=-1;dict['a']=0;i-start=-1;

i=1;start=-1;dict['b']=1;start=-1;i-start=2;

i=2;start=-1;dict['c']=2;start=-1;i-start=3;

i=3;dict['a']=0;故start=0;i-start=3;

i=4;dict['b']=1;start=1;i-start=3;

……以此类推。

特注:解决方法是leetcode中的用户lightmark提供的。此法很巧妙,于是记录下来,以供以后温习。

猜你喜欢

转载自blog.csdn.net/majalis_C/article/details/86597813