1. 程式人生 > >[LeetCode] Longest Substring Without Repeating Characters

[LeetCode] Longest Substring Without Repeating Characters

fad 設置 length clas ase set () out sts

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

解題思路

設置左右兩個指針。左右指針之間的字符沒有出現反復,則右指針向右移動。否則左指針向右移動(直到沒有反復字符為止)。而且統計最大字符數。

實現代碼

// Rumtime: 60 ms
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        set<int> res;
        int maxLen = 0;
        int left = 0;
        int i;
        for (i = 0; i < s.size(); i++)
        {
            if (res.find(s[i]) != res.end())
            {
                maxLen = max(maxLen, i - left);
                while
(s[left] != s[i]) { res.erase(s[left++]); } left++; } else { res.insert(s[i]); } } maxLen = max(maxLen, i - left); return maxLen; } };
$(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); });

    [LeetCode] Longest Substring Without Repeating Characters