题目描述
给定一个字符串 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 windowint right = 0; // Initialize the right pointer of the sliding windowint max = 0; // Initialize the maximum length of the substringint i, j;int len = strlen(s); // Get the length of the input stringint haveSameChar = 0; // Flag to indicate if there are repeating charactersfor (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 foundbreak;}}if (haveSameChar){// Move the left pointer to the next position after the repeating characterleft = j + 1;}}// Update the maximum length of the non-repeating substringmax = 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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。