读书人

求子串个数解决方法

发布时间: 2012-08-27 21:21:57 作者: rapoo

求子串个数
比如有个字符串, “http://www.qq.com”,求该字符串的子串个数。(重复的子串不增加计数,比如 w,只能算一个).需要两种办法,一种是数学方法,就是说没有电脑的情况下,怎么快速求得;另一种是写程序来求。

咋一看,很简单的样子。可是在做题的时候,硬是没有做出来。汗~~~~

[解决办法]

C# code
 string temp = "http://www.qq.com";            int count = temp.ToCharArray().Distinct().Count();//11
[解决办法]
探讨

引用:
C# code

string temp = "http://www.qq.com";
int count = temp.ToCharArray().Distinct().Count();//11

NB!

[解决办法]
C# code
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            string s = "http://www.qq.com";            foreach (var item in EnumSubStrings(s))            {                Console.WriteLine(item);            }            Console.WriteLine("全部个数:" + EnumSubStrings(s).Count());            Console.WriteLine("去掉重复:" + EnumSubStrings(s).Distinct().Count());        }        static IEnumerable<string> EnumSubStrings(string s)        {            yield return "";            for (int i = 0; i < s.Length; i++)            {                for (int j = i + 1; j <= s.Length; j++)                {                    yield return s.Substring(i, j - i);                }            }        }    }}
[解决办法]
手算
http://www.qq.com,长度17
子串个数=17+16+15+14+...+1+1(空串)=(17+1)*17/2+1=154
重复
t 2
/ 2
w 3
ww 2
. 2
q 2
也就是1+1+2+1+1+1=7
所以是154-7=147。

读书人网 >C#

热点推荐