算法题——无重复字符的最长子串

拥有回忆 提交于 2019-11-27 08:09:51

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;
    }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!