360编程偶串问题

如何找出一个字符串的所有子串,并判断其中偶串的个数,偶串指所有字符出现的次数为偶数次。

def removeDuplicate(s):
    s = list(s)
    s.sort()  # 对给定字符串排序,不排序可能移除不完整
    for i in s:
        while s.count(i) > 1:
            s.remove(i)
    s = "".join(s)  # 把列表转换成字符串,不能用str(s)
    return s
while 1:
    s = raw_input()
    length = len(s)
    cnt=0

    #for i in range(length):
      #  print s[i]
    for i in range(length):
        for j in range(i,length+1):
            ss=s[i:j]
            #print len(ss)%2==0
            if (len(ss)>1) and (len(ss)%2)==0:
                #print ss
                flag = 2
                kk=removeDuplicate(ss)
                for m in range(len(kk)):
                    if ss.count(kk[m])%2!=0:
                        flag=1
                if flag == 2:
                    cnt=cnt+1
    print cnt

  上述代码太不简洁,请看下面别人的代码

 

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

s = raw_input()
length = len(s)

cnt=0
for i in range(length-1):
    for j in range(i+2,length+1,2):
        ss=s[i:j]   
        unique = set(ss)
        flag = 1
        for letter in unique:
            if ss.count(letter)%2!=0:
                flag = 0
                break
        if flag == 1:
            cnt += 1                    
print cnt

 

posted @ 2017-03-26 08:54  沐雨橙风fire  阅读(412)  评论(0编辑  收藏  举报