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

题目描述:

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

 

输入:

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

 

输出:

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

 

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

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

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main() {
 5     string s;
 6     while (cin >> s) {
 7         int *a = new int[s.length()];
 8         int max = 1;
 9         bool flag;
10         a[0] = 1;
11         for (int i = 1; i < s.length(); ++i) {
12             flag = true;
13             for (int j = 1; j <= a[i - 1]; ++j) {
14                 if (s[i - j] == s[i]) {
15                     a[i] = j;
16                     flag = false;
17                     break;
18                 }
19             }
20             a[i] = flag ? a[i - 1] + 1 : a[i];
21             max = max > a[i] ? max : a[i];
22         }
23         cout << max << endl;
24     }
25     return 0;
26 }

 滑动窗口!

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <algorithm>
 5 using namespace std;
 6  
 7 string s;
 8 vector<int> pos;
 9  
10 void solve() {
11     int start = 0, len = 0;
12     pos.assign(256, -1);
13     for (int i = 0; i < s.length(); ++i) {
14         if (pos[s[i]] >= start) {
15             start = pos[s[i]] + 1;
16         } else {
17             len = max(len, i - start + 1);
18         }
19         pos[s[i]] = i;
20     }
21     cout << len << endl;
22 }
23  
24 int main() {
25     while (cin >> s) {
26         solve();
27     }
28     return 0;
29 }
30 /**************************************************************
31     Problem: 1530
32     User: hupo250
33     Language: C++
34     Result: Accepted
35     Time:50 ms
36     Memory:1520 kb
37 ****************************************************************/

 

 

posted @ 2014-04-01 20:58  Eason Liu  阅读(278)  评论(0编辑  收藏  举报