LeetCode3:无重复字符的最长子串

题目

LeetCode3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。

题解

当我们知道该字符集比较小的时侯,我们可以用一个整数数组作为直接访问表来替换 Map。
字符hash对应常用的表如下所示:
int [26] 用于字母 ‘a’ - ‘z’或 ‘A’ - ‘Z’
int [128] 用于ASCII码
int [256] 用于扩展ASCII码

C++实现

#include <iostream>
#include <vector>
#include <string>
#include <map>

using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int  size,i=0,j,k,max=0;
        for(j = 0;j<s.size();j++){
            for(k = i;k<j;k++)
                if(s[k]==s[j]){
                    i = k+1;
                    break;
                }
            if(j-i+1 > max)
                max = j-i+1;
        }
        return max;
    }
};

int main(int argc, const char * argv[]) {
    Solution test;
    string str = "pwwkew";
    int n = test.lengthOfLongestSubstring(str);
    cout << n;
    return 0;
}

C实现

//hash实现

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

int lengthOfLongestSubstring(char* s) {
    int n=0,max = 0,low=0;
    int hash[128];
    
    for (int i=0; i<128; i++) {
        hash[i]=-1;
    }
    for (int i =0 ; i<strlen(s); i++) {
        printf("%c %d %d %d\n",s[i],hash[s[i]],i,n);
        if (hash[s[i]]>=0 && low <= hash[s[i]]) {
            if(n>max)max = n;
            low = hash[s[i]]+1;
            hash[s[i]]=i;
            n = i - low+1;
        }else{
            hash[s[i]] = i;
            n++;
        }
    }
    if(n>max)max = n;
    return max;
}

int main(int argc, const char * argv[]) {
    char str[] ="dvdf";
    int n = lengthOfLongestSubstring(str);
    printf("%d\n",n);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值