LeetCode #3 Longest Substring Without Repeating Characters C# Solution

LeetCode 3题解析
本文解析了LeetCode第3题:寻找给定字符串中最长的无重复字符子串的问题。通过跟踪子串的起始和结束位置,记录每个字符最后出现的位置,实现了高效的遍历算法。

LeetCode #3 Problem
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.

记录目前考察的子串的开头和结尾,出现过的字母、出现过的子串的字母的位置。
从头到尾扫这个数组,每往后扫一位,如果pos位置上的字母出现过,那就吧start移动到上一个这个字母出现的位置同时end++;如果没出现过那就end++。

第一次提交的时候以为这个字符串只有字母,WA了一次……看到测试数据的我是崩溃的……

C# Code
    public class Solution
    {
        public int LengthOfLongestSubstring(string s)
        {
            int start = 0, end = 0;
            bool[] exist = new bool[300];
            int[] position = new int[300];
            for (int i = 0; i < 200; i++)
            {
                exist[i] = false;
                position[i] = 0;
            }
            for (int i = 0; i < s.Length; i++)
            {
                if (exist[s[i]] == true)
                {
                    for (int j = start; j <= position[s[i]]; j++) exist[s[j]] = false;
                    start = position[s[i]] + 1;
                    exist[s[i]] = true;
                    position[s[i]] = i;
                }
                else
                {
                    exist[s[i]] = true;
                    position[s[i]] = i;
                    if (end <= i - start + 1) end = i - start + 1;
                }
            }
            return end;
        }
    }

这里写图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值