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.


思路:

方法1:通过Bitmap来统计是否子字符串中有重复的字符。遍历时若遇到重复值,需要回溯。 方法2:通过一个数字来存储每一个字符上一次出现的位置,当出现冲突时及时调整。

代码:

方法1:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    
        if(s.size() == 0)
        {
            return 0;
        }
        else
        {
            bool* bm = new bool[26];
            for(int i = 0; i <26; i++)
            {
                bm[i] = false;
            }
            
            int max = 1;
            int count = 0;
            for(int i = 0; i < s.size(); i++)
            {
                if(!bm[s[i] - 'a'])
                {
                    count += 1;
                    bm[s[i] - 'a'] = true;
                }
                else
                {
                    if(max < count)
                    {
                        max = count;
                    }
                    
                    for(int k = i - count; k < i; k++)
                    {
                        if(s[i] == s[k])
                        {
                            i = k;
                        }
                    }
                    
                    count = 0;
                    for(int j = 0; j <26; j++)
                    {
                        bm[j] = false;
                    }
                    
                }
            }
            if(max < count)
            {
                max = count;
            }
            return max;
        }
        
    }
};

方法2:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int pos[512];
        for(int i = 0; i < 512; i++){
            pos[i] = -1;
        }
        
        int max = 0;
        int min = 0;
        for(int i = 0; i < s.size(); i++){
            if(pos[s[i]] == -1){
                pos[s[i]] = i;
            }
            else{
                if(i - min > max){
                    max = i - min;
                }
                for(int j = 0; j < 512; j++){
                    if(pos[j] != -1 && pos[j] < pos[s[i]]){
                        pos[j] = -1;
                    }
                }
                min = pos[s[i]] + 1;
                pos[s[i]] = i;
            }
        }
        if(s.size() - min > max){
            max = s.size() - min;
        }
        return max;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11715169
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞