笔试算法题及解答(Python)
1、给定任意一个正整数,求比这个数大且最小的“不重复数”,“不重复数”的含义是相邻两位不相同,例如1101是重复数,而1201是不重复数
1 # coding:utf-8 2 ''' 3 Created on 2015年8月11日 4 Q1: 给定任意一个正整数,求比这个数大且最小的“不重复数”,“不重复数”的含义是相邻两位不相同,例如1101是重复数,而1201是不重复数 5 @author: Hongzm 6 ''' 7 8 def judgeRepetNum(numArr): 9 size = len(numArr) 10 for i in range(size-1): 11 if(numArr[i] == numArr[i+1]): 12 return True 13 return False 14 15 if __name__ == '__main__': 16 num = 112340 17 while(num<9900000000): 18 numArr = list(str(num)) 19 if not judgeRepetNum(numArr): 20 print num 21 break 22 else: 23 num += 1
2、长度为N(N很大)的字符串,求这个字符串里的最长回文子串
# coding:utf-8 ''' Created on 2015年8月11日 Q2: 长度为N(N很大)的字符串,求这个字符串里的最长回文子串 @author: Hongzm ''' import re # manacher算法 def manacherStr(str): # p记录每个节点回文子串半径 p = [] mx = 0 id = 0 size = len(str) for i in range(1, size-1): p[i] = min(p[2*id-i], mx -1) if mx>i else 1 while(str[i + p[i]] == str[i-p[i]]): p[i]+=1 if(i + p[i]>mx): mx = i + p[i] id = i print p def palindromeStr(words): print "start" maxLen = 0 index = 0 size = len(words) for i in range(1, size-1): print "i = ", i, words[i] tempLen = 0 for j in range(1, min(i, size-i)): print "j = ", j if(words[i-j]==words[i+j]): tempLen += 1 else: break print "tempLen = ", tempLen if(tempLen > maxLen): maxLen = tempLen index = i print "maxLen = ", maxLen return words[index-maxLen:index+maxLen+1] if __name__ == '__main__': str_origin = "fabbacddcabh" str_ = "-" + "-".join(str_origin) + "-" str_end = palindromeStr(str_) print str_end.replace('-',"") print re.sub("python", "word", "hello, python")
3、数轴上从左到右有n各点a[0], a[1], ……,a[n -1],给定一根长度为L的绳子,求绳子最多能覆盖其中的几个点
# coding:utf-8 ''' Created on 2015年8月11日 Q3、数轴上从左到右有n各点a[0], a[1], ……,a[n -1],给定一根长度为L的绳子,求绳子最多能覆盖其中的几个点 @author: Hongzm ''' theLen = 26 oriArr = [-20, -10, -5, 0 , 1, 6, 10, 18, 25] lenArr = [] oriSize = len(oriArr) for i in range(oriSize-1): lenArr.append(oriArr[i+1] - oriArr[i]) # print lenArr maxNum = 0 index = 0 lenSize = len(lenArr) for i in range(lenSize): tempLen = 0 temp = 0 j= 0 while(tempLen <= theLen and j< lenSize-i): temp +=1 tempLen += lenArr[i+j] j +=1 if(temp > maxNum): maxNum = temp index = i print maxNum, index print oriArr[index:index+maxNum]