|
|
|
|
|
|
y***m 发帖数: 7027 | 1 土办法:
static int indexOf(string sourceStr, string targetStr)
{
if (sourceStr == null || targetStr == null)
throw new Exception("Null point excetion.");
if (targetStr.Length == 0) return 0;
if (targetStr.Length > sourceStr.Length) return -1;
char c = targetStr[0];
for (int i = 0; i < sourceStr.Length; i++)
{
if (sourceStr[i].Equals(c))
{
int Length = 1;
for (int j = 1; j < targetStr.Length && (i + j) < sourceStr.Length;
j++)
{
if (sourceStr[i + j].Equals(targetStr[j])) //break;
Length++;
}
if (Length == targetStr.Length)
return i;
}
}
return -1;
}
| m*********e 发帖数: 55 | 2 KMP
经典算法
【在 y***m 的大作中提到】 : 土办法: : static int indexOf(string sourceStr, string targetStr) : { : if (sourceStr == null || targetStr == null) : throw new Exception("Null point excetion."); : if (targetStr.Length == 0) return 0; : if (targetStr.Length > sourceStr.Length) return -1; : char c = targetStr[0]; : for (int i = 0; i < sourceStr.Length; i++) : {
|
|
|
|
|
|