Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
solutions:
用一个256大小的bool数组以哈希方法查看某字符是否已经出现过。
如果没有出现过,则标记其数组对应位为true,若对应位已经为true,则从当前位向前回溯。同时用一个last标记已经查找过的字符的下一位,
如“dvdf”当前字符为'd'的时候,last则标记为'v'的位置。以减少回溯的数量。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLength=0;
int last = 0;
// map<char, bool> m;
bool *m=new bool[256];
memset(m, 0, 256);
vector<int> v;
int i=0;
for(i=0; i<s.size(); ++i) {
if(m[s[i]] == false) {
m[s[i]] = true;
// v.push_back(s[i]);
}
else {
if(i-last > maxLength) {
maxLength=i-last;
}
// vector<int>::iterator it=v.begin();
for(int j=i-1; j>=last; --j) {
if(s[j] == s[i]) {
last=j+1;
break;
}
}
}
}
return maxLength>i-last?maxLength:i-last;
}
};
以下是http://www.2cto.com/kf/201309/245623.html写的。
这种情况最好的做法就是用双指针对原串扫描,能在线性的时间解决。
i表示满足条件的字符串的起始位置,j表示结束位置。
j每次往前移动一次,遇到一个新的字符元素,判断当前的集合中是否已经存在这个字母,如果存在,移动i指针,直到排除之前出现过的这个元素。
类似贪心的思想,两个指针维护了以j结束的最长的满足条件的字符串,因此能得到最优解。
这中算法同样能够解决类似的题目例如每种元素最多出现n次的字符串,只需要用sign数组记录出现的次数并判断。