leetcode 3 : Longest Substring Without Repeating Characters 最長無重複子串 (C# 語言版)

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


思路是建立表,將字符串轉爲字符數組,添加該數組第一個字符至表中,然後對後續數組內容進行遍歷,如果contain跳出循環,否則添加下一個字符,知道跳出循環,最後得出list長度。但是對於該算法複雜度概念不足,不知道算不算簡便。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace longestsubstringwithoutrepeatcharacter
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p=new Program();
            string teststring="ofdagslnglkrnqogfdsgrshtgejyterrtw";
            int result = p.longestsubstringlength(teststring);
            Console.WriteLine("最長無重複子串長度爲 "+result);
        }

        public int longestsubstringlength(string s)
        {
            char[] ch = s.ToCharArray();
            List<char> charlist = new List<char>();
            int res;
            charlist.Add(ch[0]);
            for(int i=1;i<ch.Length;i++)
            {
                if (charlist.Contains(ch[i]))
                    break;
                else
                    charlist.Add(ch[i]);

            }
            res = charlist.Count;
            return res;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章