forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestSubstringWithoutRepeatingCharacters.cpp
71 lines (62 loc) · 1.93 KB
/
longestSubstringWithoutRepeatingCharacters.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Source : https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
// Author : Hao Chen
// Date : 2014-07-19
/**********************************************************************************
*
* Given a string, find the length of the longest substring without repeating characters.
* For example, the longest substring without repeating letters for "abcabcbb" is "abc",
* which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
*
**********************************************************************************/
#include <string.h>
#include <iostream>
#include <string>
#include <map>
using namespace std;
int lengthOfLongestSubstring1(string s) {
map<char, int> m;
int maxLen = 0;
int lastRepeatPos = -1;
for(int i=0; i<s.size(); i++){
if (m.find(s[i])!=m.end() && lastRepeatPos < m[s[i]]) {
lastRepeatPos = m[s[i]];
}
if ( i - lastRepeatPos > maxLen ){
maxLen = i - lastRepeatPos;
}
m[s[i]] = i;
}
return maxLen;
}
//don't use <map>
int lengthOfLongestSubstring(string s) {
const int MAX_CHARS = 256;
int m[MAX_CHARS];
memset(m, -1, sizeof(m));
int maxLen = 0;
int lastRepeatPos = -1;
for(int i=0; i<s.size(); i++){
if (m[s[i]]!=-1 && lastRepeatPos < m[s[i]]) {
lastRepeatPos = m[s[i]];
}
if ( i - lastRepeatPos > maxLen ){
maxLen = i - lastRepeatPos;
}
m[s[i]] = i;
}
return maxLen;
}
int main(int argc, char** argv)
{
string s = "abcabcbb";
cout << s << " : " << lengthOfLongestSubstring(s) << endl;
s = "bbbbb";
cout << s << " : " << lengthOfLongestSubstring(s) << endl;
s = "bbabcdb";
cout << s << " : " << lengthOfLongestSubstring(s) << endl;
if (argc>1){
s = argv[1];
cout << s << " : " << lengthOfLongestSubstring(s) << endl;
}
return 0;
}