【LeetCode】117.Longest Substring Without Repeating Characters

题目描述(Medium)

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

题目链接

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

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.

算法分析

从左往右扫描,当遇到重复字母时,以上一个重复字母的index+1作为新的搜索起始位置,直到最后一个字母。

判断条件为:last[s[i]] >= start,而不要使用last[s[i]] != -1,否则无法处理尾字符重复的情况。

提交代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        const int ASCII_MAX = 128;
        int last[ASCII_MAX];
        int start = 0, length = 0;
        
        fill(last, last + ASCII_MAX, -1);
        
        for (int i = 0; i < s.size(); ++i) {
            if (last[s[i]] >= start)
            {
                length = max(length, i - start);
                start = last[s[i]] + 1;
            }
            last[s[i]] = i;
        }
        length = max(length, (int)s.size() - start);
        return length;
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/83413832