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