LeetCode3. Longest Substring Without Repeating Characters
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.
题目分析 :一看到题目,第一时间想到的就是用set,但是觉得用set还不如直接用一个a[256]的数组。然后用一个max来记录最大长度,然后用了O(n^2)的时间复杂度来实现。
自己的代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//set<char> tset;
if (s.empty()) return 0;
int tmax = 1;
int i, j;
for (i = 0; i < s.size() - 1 - tmax + 1; i++) {
char a[257] = { 0 };
a[s[i]] = 1;
for (j = i + 1; j < s.size(); j++) {
if (a[s[j]] == 0) {
a[s[j]]++;
}
else {
tmax = tmax > j - i ? tmax : j - i;
break;
}
}
int size = 0;
for (int k = 0; k < 256; k++) {
if (a[k]) size++;
}
tmax = tmax > size ? tmax : size;
}
//tmax = tmax > tset.size() ? tmax : tset.size();
return tmax;
}
};但是觉得自己的复杂度有点高,看了一下别人的算法,只用了O(n)的时间复杂度。
代码如下:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
本文提供LeetCode第3题“无重复字符的最长子串”的两种解法,一种为O(n²)复杂度,另一种则更为高效,仅使用O(n)的时间复杂度。文章详细解析了每种方法的实现过程。
704

被折叠的 条评论
为什么被折叠?



