【Leetcode 3】Longest Substring Without Repeating Characters
程序员文章站
2022-07-13 21:30:06
...
题意:给定一个字符串,求出最长的子串,这个子串中要求不能有相同的字符。
思路:hash的思想,开个一个数组记下前一个相同字符的位置,然后在遍历过程中记下最大值(相当于往前能延伸的最前面的位置),即可求解答案。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int pos[300];
memset(pos,-1,sizeof(pos));
int ans=0;
int now_max=-1;//往前能延伸的最前面的位置
for(int i=0;i<s.length();++i){
if(pos[s[i]]>now_max)
now_max=pos[s[i]];
ans=max(i-now_max,ans);
pos[s[i]]=i;
}
return ans;
}
};
提交结果:
推荐阅读
-
Longest Substring Without Repeating Characters
-
LeetCode - 3.Longest Substring Without Repeating Characters(388ms)
-
[LeetCode]3.Longest Substring Without Repeating Characters
-
Leetcode_3. Find the longest substring without repeating characters
-
3-Longest Substring Without Repeating Characters @LeetCode
-
Longest Substring Without Repeating Characters (leetcode 3)
-
【Leetcode 3】Longest Substring Without Repeating Characters
-
Leetcode 3 Longest Substring Without Repeating Characters
-
leetcode【3】Longest Substring Without Repeating Characters
-
LeetCode(3)Longest Substring Without Repeating Characters