题目:找出一个字符串中长度最长并且不含重复字符的子字符串;
要解决这个问题有多种解法,在这里我们来实现一种时间复杂度最小的方法,使用了哈希值
代码如下:最终,时间复杂度为O(n),是用空间换时间来实现的。
//最长字符,开始位置的索引
public int startIndex = 0;
//最长字符结束位置的索引
public int endIndex = 0;
/// <summary>
/// 求出最长且不重复的子字符
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public int GetMaxLengthStr(char[] ch)
{
int start = 0;//当前检测的开始位置的索引
int end = ch.Length;
int maxLenght = 0;
Hashtable hashtable = new Hashtable();
for (int i = 0; i < 128; i++)
{
hashtable.Add(i,-1);//对表进行初始化
}
//对字符进行遍历
for (int i = 0; i < end; i++)
{
int value = ch[i];//取出每个字符对应的ASCII代码
if ((int)hashtable[value] > start)//在检测的范围内
{
int length = (int)hashtable[value] - start + 1;
if (length > maxLenght)//进行判断,获取最大值
{
maxLenght = length;
startIndex = start;
endIndex = i-1;
}
start = (int)hashtable[value] + 1;//对start索引进行更新
}
else
{
hashtable[value] = i;//对当前字符对应的索引赋值或者更新
}
}
int length_1 = end - start;//结尾处需要特殊的处理
if (length_1 > maxLenght)
{
maxLenght = length_1;
startIndex = start;
endIndex = end-1;
}
return maxLenght;
}