题目描述
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为1。
来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/lo…
实现
- 首先字符串内包含的元素ASCII码最多128个
- 循环处理字符串中的字符
- 遇到重复元素,则从重复元素后面的元素开始,重新计算
int lengthOfLongestSubstring(char * s)
{
int num = 0;
char hash[128] = {0}; // char类型是为了下面memset用方便
int result = 0;
if (s == NULL) {
return 0;
}
if (strlen(s) == 1) {
return 1;
}
for (int i = 0; i < strlen(s); i++) {
if (hash[s[i]] == 0) { // 不重复,hash中存放字符对应的下标+1
num++;
hash[s[i]] = i + 1;
if (num > result) {
result = num;
}
} else {
i = hash[s[i]] - 1;
num = 0;
memset(hash, 0, 128); // 从重复元素后面一个元素开始
}
}
return result;
}