본문 바로가기

Programing/Algorithm

[LeetCode] 3. Longest Substring Without Repeating Characters

728x90

 

 

 

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

 

public class Solution {
    public int LengthOfLongestSubstring(string s)
    {
        int anwser = 0;
        int startIndex = 0;

        var set = new HashSet<char>();

        for (int i = 0; i < s.Length; i++)
        {
            var c = s[i];

            if (set.Contains(c))
            {
                anwser = Math.Max(anwser, set.Count);

                set.Remove(s[startIndex++]);
                --i;
            }
            else
            {
                set.Add(c);
            }
        }

        return Math.Max(anwser, set.Count);
    }
}

 

 

 

728x90

'Programing > Algorithm' 카테고리의 다른 글

[LeetCode] 6. Zigzag Conversion  (0) 2025.02.07
[LeetCode] 5. Longest Palindromic Substring  (0) 2025.02.07
[LeetCode] 4. Median of Two Sorted Arrays  (0) 2025.01.21
[LeetCode] 2. Add Two Numbers  (0) 2025.01.20
[LeetCode] 1. Two Sum  (0) 2025.01.20