asp.net 取出两个字符串中相同的字符串
stringstr1="186,166,170,167,171,172";stringstr2="172,176,175,179,174,178,";要求最后输出结果17...
string str1 = "186,166,170,167,171,172";
string str2 = "172,176,175,179,174,178,";
要求最后输出结果 172, 展开
string str2 = "172,176,175,179,174,178,";
要求最后输出结果 172, 展开
1个回答
展开全部
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
string str1 = "complexity";string str2 = "flexibility";int[,] num = new int[str1.Length, str2.Length];int maxLen = 0;int lastSubsBegin = 0;
StringBuilder sequenceBuilder = new StringBuilder();for (int i = 0; i < str1.Length; i++)
{
for (int j = 0; j < str2.Length; j++)
{
if (str1[i] != str2[j])
num[i, j] = 0;
else
{
if (i == 0 || j == 0)
num[i, j] = 1;
else
num[i, j] = 1 + num[i - 1, j - 1];
if (num[i, j] > maxLen)
{
maxLen = num[i, j];
int thisSubsBegin = i - num[i, j] + 1;
if (lastSubsBegin == thisSubsBegin)
{
// If the current LCS is the same as the last time this block ran
sequenceBuilder.Append(str1[i]);
}
else
{
// Reset the string builder if a different LCS is found
lastSubsBegin = thisSubsBegin;
sequenceBuilder.Length = 0;
sequenceBuilder.Append(str1.Substring(lastSubsBegin, (i + 1) - lastSubsBegin));
}
}
}
}
}
Output.Text = string.Format("The longest common substring of '{0}' and '{1}' is '{2}'.",
str1, str2, sequenceBuilder.ToString());
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
string str1 = "complexity";string str2 = "flexibility";int[,] num = new int[str1.Length, str2.Length];int maxLen = 0;int lastSubsBegin = 0;
StringBuilder sequenceBuilder = new StringBuilder();for (int i = 0; i < str1.Length; i++)
{
for (int j = 0; j < str2.Length; j++)
{
if (str1[i] != str2[j])
num[i, j] = 0;
else
{
if (i == 0 || j == 0)
num[i, j] = 1;
else
num[i, j] = 1 + num[i - 1, j - 1];
if (num[i, j] > maxLen)
{
maxLen = num[i, j];
int thisSubsBegin = i - num[i, j] + 1;
if (lastSubsBegin == thisSubsBegin)
{
// If the current LCS is the same as the last time this block ran
sequenceBuilder.Append(str1[i]);
}
else
{
// Reset the string builder if a different LCS is found
lastSubsBegin = thisSubsBegin;
sequenceBuilder.Length = 0;
sequenceBuilder.Append(str1.Substring(lastSubsBegin, (i + 1) - lastSubsBegin));
}
}
}
}
}
Output.Text = string.Format("The longest common substring of '{0}' and '{1}' is '{2}'.",
str1, str2, sequenceBuilder.ToString());
追问
大哥 咱别复制别人的好吧~再说最后输出的结果也不对啊!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询