Skip to content

Instantly share code, notes, and snippets.

@non-static
Created January 8, 2014 07:05
Show Gist options
  • Save non-static/8312912 to your computer and use it in GitHub Desktop.
Save non-static/8312912 to your computer and use it in GitHub Desktop.
http://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ Calculating the length of the longest substring without duplicated characters 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…
#include <string>
#include <map>
#include <iostream>
using namespace std;
class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (s.length() == 0)
return 0;
if (s.length() == 1)
return 1;
unsigned int maxLength = 0;
unsigned int start = 0;
unsigned int i = 0;
while (i < s.length())
{
bool existing = false;
unsigned int j = start;
for (j = start; j < i; j++)
{
if (s[j] == s[i])
{
existing = true;
break;
}
}
if (!existing)
{
i++;
}
else
{
maxLength = (maxLength < i - start) ? i - start : maxLength;
start = j + 1;
}
}
maxLength = (maxLength < i - start) ? i - start : maxLength;
return maxLength;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Solution s;
int result = -1;
string str;
str = "";
result = s.lengthOfLongestSubstring(str);
cout << "[" << str << "]" << endl;
cout << result << endl;
str = "a";
result = s.lengthOfLongestSubstring(str);
cout << "[" << str << "]" << endl;
cout << result << endl;
str = "ab";
result = s.lengthOfLongestSubstring(str);
cout << "[" << str << "]" << endl;
cout << result << endl;
str = "aa";
result = s.lengthOfLongestSubstring(str);
cout << "[" << str << "]" << endl;
cout << result << endl;
str = "abc";
result = s.lengthOfLongestSubstring(str);
cout << "[" << str << "]" << endl;
cout << result << endl;
str = "aba";
result = s.lengthOfLongestSubstring(str);
cout << "[" << str << "]" << endl;
cout << result << endl;
str = "abcbabccbaedfg";
result = s.lengthOfLongestSubstring(str);
cout << "[" << str << "]" << endl;
cout << result << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment