Come from : [https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/]
3. Longest Substring Without Repeating Characters
1.Question
Given a string, find the length of the longest substring without repeating characters.
Example 1 :
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2 :
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3 :
Input: "pwwkew"
Output: 3
Explanation: 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.Answer
medium 类型题目。(稍后补充思路。。。睡觉去了)。
时间复杂度O(n),空间复杂度O(n),使用哈希表,滑动窗口。
算法思路见下图:
AC代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int begin = 0; //窗口的头指针
int result = 0;
string word = "";
int char_map[128] = {0};
for(int i = 0; i < s.length(); ++i)
{
char_map[s[i]]++;
if(char_map[s[i]] == 1) //等于1 表示word中 没有出现该字符
{
word += s[i];
if(result < word.length())
{
result = word.length();
}
}
else
{ //将重复的 s[i]删去
while(begin < i && char_map[s[i]] > 1)
{
--char_map[s[begin]];
++begin;
}
word = "";
for(int j = begin; j <= i; ++j) //重新更新 word
{
word += s[j];
}
}
}
return result;
}
};
3.大神解答
速度排名第一,明天仔细看下。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int size,i=0,j,k,max=0;
size = s.size();
for(j = 0;j<size;j++){
for(k = i;k<j;k++)
if(s[k]==s[j]){
i = k+1;
break;
}
if(j-i+1 > max)
max = j-i+1;
}
return max;
}
};
4.我的收获
字符串与哈希表的集合。
fighting。。。
扫描二维码关注公众号,回复:
6731223 查看本文章
2019/6/19 胡云层 于南京 104