using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Test
{
public class BM
{
public BM() { }
StringBuilder contextCache = new StringBuilder();
List<int> startIndex = new List<int>();
List<int> endIndex = new List<int>();
public void SetCache(string[] context)
{
if (contextCache.Length == 0)
{
for (int i = 0; i < context.Length; i++)
{
startIndex.Add(contextCache.Length);
setCache(context[i]);
endIndex.Add(contextCache.Length - 1);
}
}
}
public void SetCache(string context)
{
if (contextCache.Length == 0)
{
setCache(context);
}
}
void setCache(string context)
{
contextCache.Append(context);
}
public void ClearCache()
{
contextCache.Clear();
startIndex.Clear();
endIndex.Clear();
}
/// <summary>
/// 搜索字符串索引
/// </summary>
/// <param name="targetMsg">要搜索的字符串</param>
/// <returns>根据缓存数据类型确定返回数据类型,缓存的数组则返回数组索引,缓存字符串则返回字符索引</returns>
public int[] GetIndex(string targetMsg)
{
return getIndex(targetMsg);
}
/// <summary>
/// 搜索字符串索引
/// </summary>
/// <param name="targetMsg">要搜索的字符串数组</param>
/// <returns>根据缓存数据类型确定返回数据类型,缓存的数组则返回数组索引,缓存字符串则返回字符索引</returns>
public int[][] GetIndex(string[] targetMsg)
{
int[][] result = new int[targetMsg.Length][];
for (int i = 0; i < targetMsg.Length; i++)
{
result[i] = getIndex(targetMsg[i]);
}
return result;
}
List<char> temparray = new List<char>();
List<int> result = new List<int>();
int[] getIndex(string targetMsg)
{
result.Clear();
temparray.Clear();
temparray.AddRange(targetMsg);
for (int i = temparray.Count - 1; i < contextCache.Length;)
{
int moveCount = temparray.Count-1;
if (temparray[temparray.Count - 1] == contextCache[i])
{
for (int j = temparray.Count - 2, k = 1; j >= 0; j--, k++)
{
if (temparray[j] != contextCache[i - k])
{
moveCount -= temparray.FindIndex(0, temparray.Count - k, a => a == contextCache[i]);
break;
}
}
if (moveCount == temparray.Count - 1)
{
int charIndex = i - moveCount;
if (startIndex.Count != 0)
{
for (int j = 0; j < startIndex.Count; j++)
{
if (startIndex[j] <= charIndex && charIndex <= endIndex[j])
{
charIndex = j;
break;
}
if (j == startIndex.Count)//过滤掉由拼接字符组出现的拼接答案
{
charIndex = -1;
}
}
}
if (charIndex != -1)
result.Add(charIndex);
moveCount = 1;
}
}
else
{
for (int j = temparray.Count - 1; j >= 0; j--)
{
if (temparray[j] == contextCache[i])
{
moveCount -= j;
break;
}
if (j == 0)
{
moveCount -= -1;
}
}
}
i += moveCount;
}
return result.ToArray();
}
}
}