【力扣 - 无重复字符的最长字符串】

题目描述

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3

示例 2:

输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1

示例 3:

输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。

提示:

0 <= s.length <= 5 * 10^4
s 由英文字母、数字、符号和空格组成

题解

滑动窗口

在这里插入图片描述
在这里插入图片描述

代码

// Function to find the length of the longest substring without repeating characters
int lengthOfLongestSubstring(char *s)
{
    int left = 0; // Initialize the left pointer of the sliding window
    int right = 0; // Initialize the right pointer of the sliding window
    int max = 0; // Initialize the maximum length of the substring
    int i, j;
    int len = strlen(s); // Get the length of the input string
    int haveSameChar = 0; // Flag to indicate if there are repeating characters

    for (i = 0; i < len; i++)
    {
        if (left <= right)
        {
            haveSameChar = 0; // Reset the flag for repeating characters

            // Check for repeating characters within the current window [left, right]
            for (j = left; j < right; j++)
            {
                if (s[j] == s[right])
                {
                    haveSameChar = 1; // Set the flag if a repeating character is found
                    break;
                }
            }

            if (haveSameChar)
            {
                // Move the left pointer to the next position after the repeating character
                left = j + 1;
            }
        }

        // Update the maximum length of the non-repeating substring
        max = max < (right - left + 1) ? (right - left + 1) : max;

        right++; // Expand the window by moving the right pointer
    }

    return max; // Return the length of the longest substring without repeating characters
}

作者:我自横刀向天笑
链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters/solutions/1192065/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-u22kb/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六月悉茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值