iT邦幫忙

0

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

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

乍看之下,原意將字符串中的字符遍歷,記錄每個字符的位置,
遇到相同的字符更新位置,然後比較長度。

來看看㊣官方範例↓
https://ithelp.ithome.com.tw/upload/images/20201106/20132436s5ipmj3lX6.png

看完範例後,如果你的感想是這樣的話↓
https://ithelp.ithome.com.tw/upload/images/20201106/201324361x8AmDBYp6.jpg
https://ithelp.ithome.com.tw/upload/images/20201106/20132436XyEAvjooHK.jpg
https://ithelp.ithome.com.tw/upload/images/20201106/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);
    }
}

看看執行結果
https://ithelp.ithome.com.tw/upload/images/20201106/20132436Iik4aWXawH.png


尚未有邦友留言

立即登入留言