1. 程式人生 > >【LeetCode】117.Longest Substring Without Repeating Characters

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