题目
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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
};
思路
从左到右遍历,每个字母都与从head到它本身的所有字母比较是否相同,如果相同,则说明当前的substring已经不能再扩大了,将其长度与当前最大值取最大,并且将head直接移动到与当前字母(i)相同的字母(j)处的下一个,这样可以尽可能的减少重复的比较,因为上一个head第j个字母之间的每个字母作为head,到第i个字母时都会因为第j个字母的相同而使substring无法扩大,substring都小于上一个head到第i个字母。假设string长度为n,第一个循环将进行n次,第二个循环次数不会超过26(若全为小写)。
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int head = 0, max = 0, current = 0;
int size = s.size();
int i, j;
for (i = 0; i < size; i++) {
for (j = head; j < i; j++) {
if (s[j] == s[i]) {
break;
}
}
if (j == i) {
current++;
} else {
if (current > max) {
max = current;
}
current = current-(j-head);//从新的head到当前字母位置的substring的长度
head = j+1;//移动head
}
}
if (current > max) {
max = current;
}
return max;
}
};