「LeetCode」0002-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
    如非注明,原创内容遵循GFDLv1.3发布;其中的代码遵循GPLv3发布。
                    
                
                
            
        
浙公网安备 33010602011771号