1. 程式人生 > >「LeetCode」0003- Longest Substring Without Repeating Characters(C++)

「LeetCode」0003- Longest Substring Without Repeating Characters(C++)

分析

貪心思想。注意更新每次判斷的最長不同子串的左區間的時候,它是必須單調增的(有時候會在這裡翻車)。

程式碼

關掉流同步能有效提高速度。

static const auto io_sync_off = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

class Solution
{
public:
    int lengthOfLongestSubstring(string s)
    {
        array<int, 256> m; 
        m.fill(-1);
        int maxlen=0, l=0, idx=0;
        for(auto c:s)
        {
            l=max(l,m[c]+1); 
            maxlen=max(maxlen,idx-l+1);
            m[c]=idx++;
        }
        return maxlen;
    }
};

改進的時間變化:24ms->20ms->8ms