`
cozilla
  • 浏览: 92113 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[LeetCode] Longest Substring Without Repeating Characters

 
阅读更多

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