求两个字符串中的公共字符串


 求两个字符串中的公共字符串,最大公共字符串.

C#简单代码如下:

 1 namespace test
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             Console.WriteLine("获取两字符串最大的共同字符");
 8             Console.WriteLine("请输入两个字符串,中间用空格隔开");
 9             string s1=Console.ReadLine();
10             bool isGo = true;
11             if(s1.IndexOf(' ')<0)
12             {
13                 isGo = false;
14                 Console.WriteLine("输入错误");
15             }
16             string[] s = s1.Split(' ');
17 
18             if(s.Count()!=2)
19             {
20                 isGo = false;
21                 Console.WriteLine("获取错误");
22             }
23             if (isGo)
24             {
25                 List<string> maxMatchStr = new List<string>();
26                 string maxPublicStr="";
27                 foreach (string str in GetPublicStr(maxMatchStr, s[0], s[1]))
28                 {
29                     if(str.Length>maxPublicStr.Length)
30                     {
31                         maxPublicStr=str;
32                     }
33                     Console.WriteLine(str);
34                 }
35                 Console.WriteLine("共有公共字符串个数:" + maxMatchStr.Count());
36                 Console.WriteLine("最大的公共字符串:" + maxPublicStr);
37             }
38             Console.ReadKey();
39         }
40         
41         static List<string> GetPublicStr(List<string> matMatchStr, string leftStr, string rightStr)
42         {
43             for (int i = 1; i <= leftStr.Length; i++)
44             {
45                 string operatStr = leftStr.Substring(0, i);
46 
47                 if (rightStr.IndexOf(operatStr) != -1)
48                 {
49                     if (!matMatchStr.Contains(operatStr))
50                     {
51                         matMatchStr.Add(operatStr);
52                     }
53                     string tempLeftStr = leftStr.Substring(leftStr.IndexOf(operatStr) + 1);
54                     GetPublicStr(matMatchStr, tempLeftStr, rightStr);
55                 }
56             }
57             return matMatchStr;
58         }
59     }
60 }

无聊打打小例子,哈哈.

转载于:https://www.cnblogs.com/9546-blog/archive/2012/09/14/GetPublicStr.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值