1. 题目
Given a string, find the length of the longest substring without repeating characters.
Examples:
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.
https://leetcode.com/problems...
2. 思路
遍历计算s[i:j]的以i为起点的最长j,通过hashset判重来计算是否独立。找到一个最大的j之后,计算当前找到的以i为起点的是不是更大值,是则保持。然后冲i开始往后跳跃到等于s[j+1]字符的位置的下一个位置作为新的i起点。跳跃时经过的字符从hashset中清除。
整体复杂度是O(N)
3. 代码
耗时:16ms
#include <string>
//#include <unordered_set>
class HashSet {
public:
HashSet() {
clear();
}
void clear() {
for (int i = 0; i < 256; i++) {
_s[i] = false;
}
}
bool has(char c) {
return _s[c + 128];
}
bool insert(char c) {
int i = c + 128;
bool ret = _s[i];
_s[i] = true;
return ret;
}
void erase(char c) {
_s[c + 128] = false;
return ;
}
private:
bool _s[256];
};
class Solution {
public:
int lengthOfLongestSubstring(const string& s) {
h.clear();
int i = 0;
int j = 0;
int len = s.length();
int max = 0;
int max_i = 0;
while (i < len - max && j < len) {
char cj = s[j];
//if (h.insert(cj).second) {
if (!h.insert(cj)) {
++max_i;
++j;
continue;
}
if (max_i > max) {
max = max_i;
}
while (i < j + 1) {
char ci = s[i];
h.erase(ci);
--max_i;
if (ci != cj) {
++i;
} else {
++i;
break;
}
}
}
if (max_i > max) {
max = max_i;
}
return max;
}
private:
// std::unordered_set<char> h;
HashSet h;
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。