首页 > 试题广场 >

子串计算

[编程题]子串计算
  • 热度指数:9917 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
给出一个01字符串(长度不超过100),求其每一个子串出现的次数。

输入描述:
输入包含多行,每行一个字符串。


输出描述:
对每个字符串,输出它所有出现次数在1次以上的子串和这个子串出现的次数,输出按字典序排序。
示例1

输入

10101

输出

0 2
01 2
1 3
10 2
101 2
while True:
    try:
        inp=input().strip()
        lenth=len(inp)
        dict1={}
        for i in range(1,lenth+1):
            for j in range(lenth-i+1):
                index=inp[j:j+i]

                if index not in dict1:
                    dict1[index]=1
                else:
                    dict1[index]+=1
        dict1=sorted(dict1.items(),key=lambda x:x[0])
        for i in dict1:
            if i[1]>1:
                print(i[0]+' '+str(i[1]))
    except:
        break
编辑于 2019-07-29 14:39:10 回复(0)
#既然全部循环查找所有的子串,就不使用字符串的count()方法了
while True:
    try:
        string = input()
        stringLen = len(string)
        result = {}
        for i in range(stringLen):
            for j in range(i+1,stringLen+1):
                tempSub = string[i:j]
                if tempSub not in result:
                    result[tempSub] = 1
                else:
                    result[tempSub] += 1
        result = list(filter(lambda x:x[1] != 1,result.items()))
        result.sort(key=lambda x:x[0])
        for i in result:
            print("%s %d"%(i[0],i[1]))
    except Exception:
        break

编辑于 2018-10-01 18:11:15 回复(0)
try:
    while 1:
        table = {}
        s = raw_input()
        L = len(s)
        for i in xrange(L):
            for j in xrange(i + 1, L + 1):
                current = s[i:j]
                if not current in table:
                    table[current] = 1
                else:
                    table[current] += 1
        result = sorted(filter(lambda x:x[1] != 1, table.items()),key=lambda x:x[0]) 
        for u, v in result:
            print u, v
except:
    pass

发表于 2016-12-27 18:06:16 回复(0)