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.
1.个人分析
直观的思路是从头到尾遍历一次字符串,利用两个指针,第一个指向起始处,第二个从第一个的下一个位置开始遍历,直到遇到与第一个指针相同的字符或字符串的结尾。另一种思路是借助哈希表来查找最长无重复的子串。
2.个人解法
int lengthOfLongestSubstring(string s)
{
string longSub; //保存最长子串
int strLen = s.length();
for (int i=0; i<strLen; ++i){
string tmp;
tmp.push_back(s[i]);
for (int j=i+1; j<strLen; ++j){
//查找并保存当前无重复子串
if(tmp.find(s[j]) != string::npos)
break;
tmp.push_back(s[j]);
}
//比较无重复子串长度
if(tmp.length() > longSub.length()){
longSub.assign(tmp);
}
}
return longSub.length();
}
该解法的时间复杂度为O(n^2)
3.参考解法
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;
}
该解法的时间复杂度为O(n),空间复杂度为O(1),运行结果显示时间效率非常的高。
4.总结
参考解法其实也是哈希表的一种形式,因为所有的测试字符都是ANSI II字符集,所以可以设定一个固定长度的字典。如果字符集是其他形式的话,则哈希表则是不定长的。
PS:
- 题目的中文翻译是本人所作,如有偏差敬请指正。
- 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。