//字符串算法
//题目:给定一个字符串,找到其中不含重复字符的最长子串的长度。
//
//问题函数定义:
//
//cpp
//int lengthOfLongestSubstring(const std::string& s);
//裁判测试程序样例:
//
//cpp
#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
using namespace std;
//1.滑动窗口法(推荐O(n))
int lengthOfLongestSubstring(const std::string& s) {
unordered_map<char, int> charIndexMap;
int start = 0;
int maxlen = 0;
for (int end = 0; end < s.length(); end++) {
if (charIndexMap.find(s[end]) != charIndexMap.end()) {
// 如果当前字符已经在窗口中出现过,则更新窗口的起始位置
start = max(start, charIndexMap[s[end]] + 1);
}
// 更新当前字符的最新位置
charIndexMap[s[end]] = end;
// 更新最大子串长度
maxlen = max(maxlen, end - start + 1);
}
return maxlen;
}
int main() {
std::string s = "abcabcbb";
std::cout << "Length of longest substring without repeating characters: " << lengthOfLongestSubstring(s) << std::endl;
return 0;
}
//输入样例:
//
//s = "abcabcbb"
//输出样例:
//
//Length of longest substring without repeating characters : 3
//2.暴力遍历法O(n^2)
int lengthOfLongestSubstring(const std::string& s) {
int start = 0;
int maxlen = 1;
int len = 1;
for (int i = 1; i < s.length(); i++) {
len++;
for (int j = start; j <= i - 1; j++) {
if (s[i] == s[j]) {
start = max(j + 1,start);
len = i - j;
}
}
maxlen = max(len, maxlen);
}
return maxlen;
}