您的位置:首页 > 其它

网上有些例子有问题,所以重新写了下 求字符串的最长不重复字串

2016-05-10 10:14 169 查看
假设有一个字符串“abcdebfgh”

那么最长不重复字串是"cdebfgh",长度是7

若是:abcdbefbghijij

应输出:befbghij

以abcbef这个串为例

用一个数据结构pos记录每个元素曾出现的下标,初始为-1

从s[0]开始,pos['a'] == -1,说明a还未出现过,令pos['a'] = 0,视为将a"加入当前串",同时长度++

同理令pos['b'] = 1,pos['c'] = 2

到s[3]时,pos['b'] != -1,说明'b'在前面已经出现过了,此时可得到一个不重复串"abc",刷新当前的最大长度,然后做如下处理:

pos[s[0~2]] = -1,亦即将"ab""移出当前串",同时当前长度减去3

重复以上过程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{

string ss = "abcdbefbghijij";
var list = ss.ToCharArray();
int left = 0;
int right = 0;
GetLen(list, out left, out right);
Console.WriteLine(ss.Substring(left, right - left + 1));
}

/// <summary>
///
/// </summary>
/// <param name="list"></param>
/// <param name="left">right index from 0</param>
/// <param name="right">right index from 0</param>
/// <returns></returns>
public static int GetLen(char[] list, out int left, out int right)
{
if (list == null || list.Length <= 0)
{
throw new Exception("the input list length is 0");
}

int len = list.Length;
left = 0;
right = 0;
int maxLen = 0;
int start = 0;
int tempMaxLen = 0;
Dictionary<char, int> cache = new Dictionary<char, int>();
for (int i = 0; i < len; i++)
{
if (!cache.Keys.Contains(list[i]) || cache[list[i]]==-1) //这个建不存在或者有建,但是值为-1,表明这个字符还没出现过.
{
tempMaxLen++;
cache.Add(list[i], i);
}
else
{
//there is duplicated char   abcdbefgh
if (tempMaxLen > maxLen)
{
maxLen = tempMaxLen;
left = start;
right = i - 1;
}

tempMaxLen = i - cache[list[i]];
for (int j = start; j < cache[list[i]]; j++) // 注意:网上好多例子是清楚这个cache里所有的,应该是错误的;仅仅应该清楚上次重复字符前面的字符。
{
cache[list[j]] = -1;
}

start = cache[list[i]] + 1;
cache[list[i]] = i;
}
}

if (tempMaxLen > maxLen)
{
maxLen = tempMaxLen;
left = start;
right = len-1;
}

return maxLen;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: