首页 > 代码库 > LeetCode Longest Substring Without Repeating Characters

LeetCode Longest Substring Without Repeating Characters

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.

Show Tags









题意:求最长的没有重复字母的子串

思路:双指针的方法,一个指向当前子串的头(左边),一个指向尾(右边),显然如果尾指针的这个字符出现过的话,那么头指针就要跳到相应的位置了,遍历一遍找最大的

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int Max = 0;
        int cur = -1;
        int vis[256];
        memset(vis, -1, sizeof(vis));
        
        for (int i = 0; i < s.length(); i++) {
            if (vis[s[i]] > cur) 
                cur = vis[s[i]];
            Max = max(Max, i - cur);
            vis[s[i]] = i;
        }
        
        return Max; 
    }
};


LeetCode Longest Substring Without Repeating Characters