码迷,mamicode.com
首页 > 其他好文 > 详细

3.Longest Substring Without Repeating Characters

时间:2016-10-07 15:43:12      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 #include <string>
 4 #include <string.h>
 5 #include <iostream>
 6 #include <vector>
 7 using namespace std;
 8 #define debug(x) cout << #x << " at line " << __LINE__ << " is: " << x << endl
 9 int max(int a, int b){
10     return (a>b?a:b);
11 }
12 
13 int lengthOfLongestSubstring(char* s) {
14     int sidx = 0;
15     int MAXLEN = 0;
16 
17     while (s[sidx] != \0){
18         ++sidx;
19     }
20     //cout << sidx << ‘\n‘;
21 
22     for (int k = 0; k < sidx; ++k) {
23 
24         int HASHMAP[128];
25         memset(HASHMAP, 0x00, sizeof(HASHMAP));
26         HASHMAP[s[k]] = 1;
27         //debug("*******");debug(k);debug(s[k]);debug("*******");
28         //MAXLEN = 1;
29         //left
30         int llen = 0;
31         for (int i = k-1; i >= 0; ++i) {
32             if(HASHMAP[s[i]] == 0){
33                 ++llen;
34                 //debug(llen);debug(i);debug(s[i]);
35                 HASHMAP[s[i]] = 1;
36             }else if (HASHMAP[s[i]] == 1) {
37                 break;
38             }
39         }
40         //right
41         int rlen = 0;
42         for (int j = k+1; j < sidx; ++j) {
43             if(HASHMAP[s[j]] == 0){
44                 ++rlen;
45                 //debug(rlen);debug(j);debug(s[j]);
46                 HASHMAP[s[j]] = 1;
47             }else if (HASHMAP[s[j]] == 1) {
48                 break;
49             }
50         }
51 
52         if(MAXLEN < (llen + rlen+1)){
53             MAXLEN = llen + rlen+1;
54         }
55         //debug(MAXLEN);
56 
57     }
58 
59     return MAXLEN;
60 }
61 int main(void) {
62     //freopen("../in.txt", "r", stdin);
63     char a[1024];
64     memset(a, 0x00, sizeof(a));
65     scanf("%s", a);
66     getchar();
67     //cout << a << endl;
68     printf("%d\n", lengthOfLongestSubstring(a));
69 
70     return 0;
71 }

 

3.Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/guxuanqing/p/5936058.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!