[C#] LeetCode 3. Longest Substring Without Repeating Charact

Given a string s, find the length of the longest substring without repeating characters.

乍看之下,原意将字符串中的字符遍历,记录每个字符的位置,
遇到相同的字符更新位置,然后比较长度。

来看看㊣官方範例↓
http://img2.58codes.com/2024/20132436s5ipmj3lX6.png

看完範例后,如果你的感想是这样的话↓
http://img2.58codes.com/2024/201324361x8AmDBYp6.jpg
http://img2.58codes.com/2024/20132436XyEAvjooHK.jpg
http://img2.58codes.com/2024/20132436yxejfyxYOE.jpg

没关係~看看我的解法吧!

public class Solution {    public int LengthOfLongestSubstring(string s) {        var Dict = new HashSet<char>();        var str = "";        var max = 0;        var cur = 0;        for (int i = 0; i < s.Length; i++)        {            if (Dict.Contains(s[i]))            {                max = Math.Max(str.Length, max);                str = "";                Dict.Clear();                i = (++cur);            }            Dict.Add(s[i]);            str += s[i];        }        return Math.Max(max, str.Length);    }}

看看执行结果
http://img2.58codes.com/2024/20132436Iik4aWXawH.png


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章