1. 题目描述(LeetCode3)
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.
2. 解决思路
这道题的关键是如何在遍历一遍字符串的时间复杂度(O(n))的情况下截取子字符串并同时判断子字符串中有无重复的字符。根据提示,我们可以利用hash表hashTable[256]来保存出现过的字符,然后从头开始遍历字符串,在遍历过程中根据判断当前字符串有无出现而进行相应的操作:
1、如果当前字符串已经出现过(hashTable[str[idx]] == 1),则说明一个局部最长不重复的子串已经出现:此时判断该子串长度len是否大于mlen,若 大于则更新mlen,以及最长子串的起始位置mstart;同时将start到重复字符之间的hash表重置为0(表示没有出现过),相应的长度len也减小,然后从str[idx]的下个字符作为新的子串的开始。
2、如果当前字符ch没有出现过,则设置hashTable为1(表示出现过),并len ++。
3. 完整代码
#include <iostream>
#include <string>
using namespace std;
int getLongestUnRepeatedSubstr(const string &str){
int hashTable[256] = {0};
int start = 0;
int mstart = 0;
int mlen = 0;
int idx = 0;
int len = 0;
while (idx != str.size()){
if (hashTable[str[idx]] == 1){
if (len > mlen){
mstart = start;
mlen = len;
}
while (str[start] != str[idx]){
hashTable[str[start]] = 0;
start++;
len--;
}
start++;
}
else{
hashTable[str[idx]] = 1;
len++;
}
idx++;
}
if (len > mlen)
{
mlen = len;
mstart = start;
}
cout << str.substr(mstart, mlen) << endl;
return mlen;
}
int main(){
string str;
while (cin >> str){
cout << getLongestUnRepeatedSubstr(str) << endl;
}
return 0;
}