频道首页
目录
算法进修——力扣0003无重复字符的最长字串
收藏
0
无重复字符的最长子串
难度:中等
题目描述
给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
示例1
输入:s = "abcabcbb" 输出:3
示例2
输入:s = "bbbbb" 输出:1
示例3
输入:s = "pwwkew" 输出:3
题解
定义哈希集合,记录每一个字符是否出现过,然后根据两个指针
left
,right
的移动来对整个字符串来进行窗口移动想法代码
class Solution
{
public static void Main(String[] args)
{
string s = "pwwkew";
int max = LengthOfLongestSubstring(s);
Console.WriteLine(max);
}
public static int LengthOfLongestSubstring(string s)
{
HashSet<char> letter = new HashSet<char>();
int left = 0, right = 0;
int length = s.Length;
int count = 0, max = 0;
while (right < length)
{
if (!letter.Contains(s[right]))
{
letter.Add(s[right]);
right++;
count++;
}
else
{
letter.Remove(s[left]);
left++;
count--;
}
max = Math.Max(max, count);
}
return max;
}
}
主页
会议室
Git管理
文章
云文档
看板