3. Longest Substring Without Repeating Characters,longestrepeating
分享于 点击 1244 次 点评:20
3. Longest Substring Without Repeating Characters,longestrepeating
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.
由题意得,找出有着不重复字符的最长的字符串的长度。题目挺简单的,每次都记录字符串开始的位置start,还有在判断是否重复的时候需要记录重复的下标index,然后遇到重复字符之后的开始位置则为start + index + 1。主函数里是遍历一遍字符串就好了,但是在判断重复字符则也要遍历一遍,所以时间复杂度最坏是在O(n^2),平均为O(nlogn),代码如下:
Code(LeetCode运行32ms):
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int Max = 0;
int length = 0;
int index = 0;
int start = 0;
string temp = "";
for(int i = 0; i < s.length(); i++) {
if (!isRepeating(s[i] , temp, index)) {
length++;
} else {
Max = max(length, Max);
length = temp.length() - index;
start = start + index + 1;
temp = s.substr(start, length - 1);
}
temp += s[i];
}
Max = max(length, Max);
return Max;
}
bool isRepeating(char c, string s, int& index) {
for (int i = 0; i < s.length(); i++) {
if (c == s[i]) {
index = i;
return true;
}
}
return false;
}
};
假如改良一下判断重复这一部分的算法,那么可以得到一个O(n)的算法,参考了LeetCode里面大神的做法,使用一个数组来保存某字符上次出现的位置。Code(LeetCode运行18ms):
int lengthOfLongestSubstring(string s) {
const int ASCII_MAX = 255;
int last[ASCII_MAX];
int start = 0;
fill(last, last + ASCII_MAX, -1);
int max_len = 0;
for (int i = 0; i < s.length(); i++) {
if (last[s[i]] >= start) {
max_len = max(max_len, i - start);
start = last[s[i]] + 1;
}
last[s[i]] = i;
}
return max((int)s.length() - start, max_len);
}
相关文章
- 暂无相关文章
用户点评