zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LeetCode·每日一题·1624.两个相同字符之间的最长子字符串·模拟

LeetCode字符模拟 字符串 两个 之间 每日 相同
2023-09-27 14:26:29 时间

链接:https://leetcode.cn/problems/largest-substring-between-two-equal-characters/solution/by-xun-ge-v-h1e6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 

题目

 

示例

 

思路

思路
直接枚举数组中每一个元素,记录元素第一次出现的下标,当在次出现时,保存中间量

小问题
int hash[26] = {-1};

为什么数组初始化之后不为-1???

代码

#define MAX(a, b) ((a) > (b) ? (a) : (b))

int maxLengthBetweenEqualCharacters(char * s){
    int max = -1;
    int len = strlen(s);
    int hash[26];//记录第一次下标
    memset(hash, -1, sizeof(int) * 26);
    for(int i = 0; i < len; i++)//枚举所有元素
    {
        if(hash[s[i] - 'a'] == -1)//未出现过,记录第一次下标
        {
            hash[s[i] - 'a'] = i;
        }
        else//出现过了,保存最大中间量
        {
            max = MAX(max, i - hash[s[i] - 'a']-1);
        }
    }
    return max;
}

作者:xun-ge-v
链接:https://leetcode.cn/problems/largest-substring-between-two-equal-characters/solution/by-xun-ge-v-h1e6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。