[Jobdu] 题目1530:最长不重复子串

时间:2023-03-09 21:38:38
[Jobdu] 题目1530:最长不重复子串
题目描述:

最长不重复子串就是从一个字符串中找到一个连续子串,该子串中任何两个字符都不能相同,且该子串的长度是最大的。

输入:

输入包含多个测试用例,每组测试用例输入一行由小写英文字符a,b,c...x,y,z组成的字符串,字符串的长度不大于10000。

输出:

对于每组测试用例,输出最大长度的不重复子串长度。

样例输入:
absd
abba
abdffd
样例输出:
4
2
4

阿尔卡特2013年实习生招聘笔试题

 #include <iostream>
using namespace std; int main() {
string s;
while (cin >> s) {
int *a = new int[s.length()];
int max = ;
bool flag;
a[] = ;
for (int i = ; i < s.length(); ++i) {
flag = true;
for (int j = ; j <= a[i - ]; ++j) {
if (s[i - j] == s[i]) {
a[i] = j;
flag = false;
break;
}
}
a[i] = flag ? a[i - ] + : a[i];
max = max > a[i] ? max : a[i];
}
cout << max << endl;
}
return ;
}

滑动窗口!

 #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std; string s;
vector<int> pos; void solve() {
int start = , len = ;
pos.assign(, -);
for (int i = ; i < s.length(); ++i) {
if (pos[s[i]] >= start) {
start = pos[s[i]] + ;
} else {
len = max(len, i - start + );
}
pos[s[i]] = i;
}
cout << len << endl;
} int main() {
while (cin >> s) {
solve();
}
return ;
}
/**************************************************************
Problem: 1530
User: hupo250
Language: C++
Result: Accepted
Time:50 ms
Memory:1520 kb
****************************************************************/