DEV Community

Sunnat Qayumov
Sunnat Qayumov

Posted on

LeetCode Problem#03

Kodning vazifasi:

LengthOfLongestSubstring metodi berilgan matn ichida takrorlanmaydigan belgilardan iborat eng uzun substringning uzunligini hisoblab beradi. Va eng uzun Substring nechchi enkanligini hisoblab berdi.

Kod:

public class Solution
{
    public int LengthOfLongestSubstring(string str)
    {
        string Substring = "";
        int maxLength = 0;

        foreach(char c in str)
        {
            if(Substring.Contains(c))
            {
                int index = Substring.IndexOf(c);
                Substring = Substring.Substring(index + 1);
            }
            Substring += c;

            maxLength = Math.Max(maxLength, Substring.Length);
        }
        return maxLength;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Kodni qadamma - qadam ko'rib chiqamiz.

1. Class va metod:

public class Solution
{
    public int LengthOfLongestSubstring(string str)
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution nomli class yaratamiz. Va ichida int tipida LengthOfLongestSubstring nomli metod yaratib olamiz. Metod string str nomli parametrga ega.

2. O'zgaruvchilar:

string Substring = "";
int maxLength = 0;
Enter fullscreen mode Exit fullscreen mode
  • Substring: Hozirda tekshirilayotgan substringni saqlash uchun ishlatiladi.
  • maxLength: Topilgan eng uzun substringni uzunligini saqlaydi.

3. Substringni tekshirish:

foreach(char c in str)
{
    if(Substring.Contains(с))
    {
         int index = Substring.IndexOf(c);
         Substring = Substring.Substring(index + 1);
    }
    Substring += c;
    maxLength = Math.Max(maxLength, Substring.Length);
}
Enter fullscreen mode Exit fullscreen mode
  • Substring.Contains(c) -> agar Substring ichida belgilardan biri bo'lsa (c):
  • IndexOf(c): Substring ichida ushbu belgi qayerda ekanligini aniqlaydi.
  • Substring = Substring.Substring(index + 1) Substringni hozirgi belgidan kesib, takrorlanmaydigan substring hosil qiladi.

Takrorlanmaydigan belgini qo'shib ketish:

Substring += c;
Enter fullscreen mode Exit fullscreen mode
  • Hozirgi belgini substringga qo'shib ketadi.

Eng uzun substringni yangilash:

maxLength = Math.Max(maxLength, Substring.Length);
Enter fullscreen mode Exit fullscreen mode
  • Math.Max — Hozirgi substring uzunligi Substring.Length va maxLength orasida kattasini tanlaydi.
  • Natija: maxLength eng uzun substring bo'lib qoladi.

Natijani qaytarish:

return maxLength;
Enter fullscreen mode Exit fullscreen mode
  • Matndagi eng uzun Substringni sonini bizga qaytarib beradi.

Top comments (0)