力扣算法题——无重复字符的最长子串练习

1、做这道题的时候,开始第一个想法就是采取暴力破解的方法,即将字符串转成数组,遍历数组,利用List来判断是否出现重复,如果出现重复字符,就记录一次当前列表的长度,只保留最大长度值返回。当然实际代码执行效率挺低的。

public int LengthOfLongestSubstring(string s) {
         int _result = 0;
            if (s!= "")
            {
                List<char> _charList = new List<char>(s.ToCharArray());
                List<char> _tempList = new List<char>();
                for (int i = 0; i < _charList.Count; i++)
                {
                    char _c = _charList[i];
                    _tempList.Clear();
                    _tempList.Add(_c);
                    for (int j = i + 1; j < _charList.Count; j++)
                    {
                        if (!_tempList.Contains(_charList[j]))
                        {
                            _tempList.Add(_charList[j]);
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (_tempList.Count > _result)
                    {
                        _result = _tempList.Count;
                    }
                }

            }

            return _result;
    }

 

2、第二次尝试时,转变了思路,采用排队的方式进行判断,先将字符串转换成数组,然后再创建一个列表进行排队,将字符串数组逐个加入到列表里,如果发现列表里存在重复元素,就记录一次当前列表的长度,再找到重复元素的索引,将重复元素以及其之前的元素清空,继续添加元素进行判断。最终将计算出最长的长度值返回。

代码如下:

 public int LengthOfLongestSubstring(string s) {
         int _maxLength = 0;
            List<char> _charList = s.ToList();
            List<char> _tempList = new List<char>();
            for(int i=0;i< _charList.Count; i++)
            {
                if (!_tempList.Contains(_charList[i]))
                {
                    _tempList.Add(_charList[i]);
                    if (_maxLength < _tempList.Count) { _maxLength = _tempList.Count; }
                }
                else
                {
                    //删除发现重复元素前的序列
                    int _index = _tempList.IndexOf(_charList[i]);
                    for (int j=0;j<= _index; j++)
                    {
                        _tempList.RemoveAt(0);
                    }
                    _tempList.Add(_charList[i]);
                }
            }
            return _maxLength;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值