对应LeetCode#3 最大不重复子字符串
#include"stdafx.h"
#include "afxwin.h"
#include <set>
//概述:贪心法,使用移动窗口方法得到局部解、set容器存放已有的字符
using namespace std;
class Solution {
public:
int static lengthOfLongestSubstring(string s) {
int maxlen = 0;
set<char> charSet;
std::set<char>::iterator it;
int i = 0;
int j = 0;
while(i < s.length() && j < s.length())
{
//1)set里没有发现重复字符,将字符放入set,更新maxlen
//2)set里发现重复字符,用i从左往右删除字符,直到删除掉这个重复的字符
//3)删除掉重复的字符后,步骤1)再次成立,开始求解maxlen新一轮的局部最优解
if (charSet.find(s[j]) == charSet.end())
{
charSet.insert(s[j]);
j++;
maxlen = max(maxlen, j - i);
}
else //发现有重复的字符a,在set中开始删除string中的字符,直到删除到第一个a,然后从它下一个数据开始遍历
{
charSet.erase(s[i++]);
}
}
return maxlen;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d\n", Solution::lengthOfLongestSubstring("abcabcbb"));
system("pause");
}