论坛首页 入门技术论坛

[LeetCode] Longest Substring Without Repeating Characters

浏览 1055 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-16  

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.

 

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int len = s.size();
        int i = 0, j = 1;
        int res = 0;
        int cnt[256] = {0};
        if (len == 0) return 0;
        cnt[s[i]] ++;
        res = 1;
        while (i < j && j < len) {
            if (cnt[s[j]] == 0) cnt[s[j++]]++;
            else {
                if (j - i > res) res = j - i;
                while (cnt[s[j]] > 0) cnt[s[i++]]--;
                cnt[s[j++]]++;
            }
        } 
        if (j == len && j - i > res) res = j - i;
        return res;
    }
};

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics