LeetCode第211场 两相同字符之间的最长子字符串

LeetCode第211场 两相同字符之间的最长子字符串

algorithm design

my solution

利用hash的思想,记录每个字母出现过的位置,找到并计算。

版本一:

处理哈希冲突的时候用了头插法,把新出现的元素插在头部,感觉不够高效;其实不用处理哈希冲突,这样时间每次时间复杂度可以降到O(1),空间也可以节省一个长度为300的数组。

#include <iostream>
#include <string>
#include <memory.h>
using namespace std;

class Solution {
public:
    struct Node
    {
        int position;
        int next = -1;
    }strings[301];
    
    int heads[27];

    int maxLengthBetweenEqualCharacters(string s) {
        int max = 0;
        int has_same = 0;
        memset(heads,-1,sizeof(int)*27);
        for(int i = 0; i < s.length(); i++){
            int tmp = s[i] - 'a';
            if(heads[tmp] != -1) {
                has_same = 1;
                strings[i].next = heads[tmp];
                int position = heads[tmp];
                do{
                    if (max < (i-position-1))
                    {
                        max = i-position-1;
                    }
                    position = strings[position].next;
                }while(position != -1);
            }
            heads[tmp] = i;
        }
        if(max == 0 && !has_same) return -1;
        return max;
    }
    
};

int main(){
    char s[301];
    cin>>s;
    Solution sol;
    cout<<sol.maxLengthBetweenEqualCharacters(s);
}

Leetcode执行结果:
在这里插入图片描述

版本二

只在positions中记录了26个字母第一次出现的位置。
总时间复杂度为O(n).

class Solution {
    int positions[26];
public:
    int maxLengthBetweenEqualCharacters(string s) {
        int max = -1;
        memset(positions,-1,sizeof(int)*26);
        for (int i = 0; i < s.length(); i++)
        {
            int tmp = s[i] - 'a';
            if(~positions[tmp]){
                if(max < i - positions[tmp] - 1) max = i - positions[tmp] - 1;
            }
            else positions[tmp] = i;
        }
        return max;
    }
};

提交结果:
在这里插入图片描述

referrence

直接用的遍历,遍历找出每个字母出现的头尾位置。第一个for循环O(26),第二个O(N)

错误记录

  1. identifier “stirng” undefined.
    sol:
#include <string>
using namespace std;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值