Leetcode-无重复字符的最长子串

68.无重复字符的最长子串

题目内容:

Leetcode-无重复字符的最长子串_第1张图片

代码及思路:

1.记录所有可能的长度

2.当出现新的重复字符则去掉原始子串中的字符及其前面的字符

具体实现:

1)建立一个left指针,指向子串最左边没有出现重复字符的位置,right(遍历时的变量i)指针指向子串终点位置,那么子串的长度就为i-left+1;

2)若遍历到这个字符,哈希表中的对应值为0的话,就说明没有出现过该字符,每一次出现字符后都要对其哈希表中的数值进行更新为i+1;

#include
#include
#include
#include
using namespace std;
class Solution {
public:
	int lengthOfLongestSubstring(string s)
	{
		if (s.length() <= 0)
			return 0;
		int res = 0, left = 0;
		int len = s.length();
		unordered_map map;
		for (int i = 0; i < len; i++)
		{
			left = max(left, map[s[i]]);
			map[s[i]] = i + 1; //map存放每个字符对应的位置
			res = max(res, i - left+1);
		}
		return res;
	}
};
void main()
{
	Solution* object = new Solution();
	string str;
	getline(cin, str);
	int res = object->lengthOfLongestSubstring(str);
	cout << res << endl;
}

 

你可能感兴趣的:(Leetcode编程题)