标签:false bsp str gif 开始 pre nbsp idt bcd
一个变量count和一个结果变量res,若s[i] == s[i+1],count +=1 ,否则count= 1
def getCountStr(s): if not s: return s count = 1 res = ‘‘ for i in range(len(s)-1): if s[i] == s[i+1]: count += 1 else: res = res + s[i] + ‘_‘ + str(count)+‘_‘ count = 1 res = res + s[len(s)-count] + ‘_‘ + str(count) return res s = ‘aaabbadddffc‘ print(getCountStr(s))
要求1:采用字典来实现,比较简单。
要求2:考察排序。
#思路1:字典 def checkstr(s): if len(s) <= 1: return True dic = {} for i in range(len(s)): if s[i] in dic: return False else: dic[s[i]] = 1 return True #思路2:快速排序 def partition(s,l,r): if not s: return None pivot = s[l] index,small,big = l,l,r while index < big: if s[index] < pivot: s[small] , s[index] = s[index] , s[small] small += 1 index += 1 elif s[index] == pivot: index += 1 else: s[index] , s[big] = s[big],s[index] big -= 1 return small,index def quick_sortStr(s,l,r): if not s: return s if l<r: l1,r1 = partition(s,l,r) quick_sortStr(s,l,l1) quick_sortStr(s,r1,r) return s def checkStr(ss): if not ss: return True s = list(ss) sorts = quick_sortStr(s, 0, len(s)-1) for i in range(len(sorts)-1): if sorts[i] == s[i+1]: return False return True #堆排序 n = 0 def buildTree(arr): global n if not arr: return arr for i in range(n//2-1,-1,-1): adjustTree(arr,i) return arr def adjustTree(arr,i): global n if not arr: return arr maxIndex = i if i*2 + 1 < n and arr[i*2 +1] > arr[maxIndex]: maxIndex = i*2 + 1 if i*2+2 < n and arr[i*2+2] > arr[maxIndex]: maxIndex = i*2 +2 if maxIndex != i: arr[i] , arr[maxIndex] = arr[maxIndex] ,arr[i] adjustTree(arr,maxIndex) return arr def heapSort(arr): global n if not arr: return arr n = len(arr) buildTree(arr) while n > 0: arr[0] , arr[n-1] = arr[n-1] , arr[0] n -= 1 adjustTree(arr,0) return arr def checkStr3(s): if len(s) <= 1: return True arr = list(s) sorts = heapSort(arr) for i in range(len(sorts)-1): if sorts[i] == s[i+1]: return False return True s = ‘abcd‘ print(checkStr3(s))
一行代码:
print(len(set(s))==len(s))
def test(s,k): if not s or s == ‘‘ or k < 0 or k >= len(s): return ‘‘ uNum = 0 for i in range(k-1,-1,-1): if not s[i].isupper(): break uNum += 1 if uNum % 2 == 1: return s[k-1:k+1] if s[k].isupper(): return s[k:k+2] return s[k] s=‘aaABCDEcNCg‘ k = 7 test(s,k)
标签:false bsp str gif 开始 pre nbsp idt bcd
原文地址:https://www.cnblogs.com/Lee-yl/p/10465808.html