Longest Substring Without Repeating Characters (FROM LeetCode)

描述：

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

样例：

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.

VS源码：

#include <string>
#include <iostream>
using namespace std;

class Solution {
public:
int LengthOfLongestSubstring(string s) {
int n = s.length();
if (n == 0)//s为null
return 0;
int *res;
res = (int*)malloc(n * sizeof(int));//分配空间
int i, max=1,j;
for (i = 1;i < n;++i)//初始化res
res[i] = 0;
res[0] = 1;
for (i = 1;i < n;++i) {
if (s[i] != s[i - 1]) {//当前字符与上一个字符不等
res[i] = 1;
for (j = i - 1;j >= i - res[i - 1];--j) {
if (s[i] != s[j])
++res[i];
else
break;
}
}
else//当前字符与上一个字符相等，则从1开始计数
res[i] = 1;
}
for (i = 0;i < n;++i)//查询最大值值
if (res[i] > max)
max = res[i];
free(res);//释放空间，以防内存泄漏
res = NULL;//防止“野指针”
return max;
}

};

int main()
{
Solution *s = new Solution();
int max = 0;
max = s->LengthOfLongestSubstring(string("dvdf"));
cout << "max=" << max << endl;
return 0;
}