HJ52 计算字符串中的编辑距离
题目链接:计算字符串的编辑距离_牛客题霸_牛客网
思路:动态规划,实在是没想到啊。
代码
import sysstr1 = sys.stdin.readline().strip()
str2 = sys.stdin.readline().strip()
dp = [[0]*(len(str1)+1) for _ in range(len(str2) + 1)]
for i in range(len(str2) + 1):dp[i][0] = i
for j in range(len(str1) + 1):dp[0][j] = j
for i in range(1, len(str2)+1):for j in range(1, len(str1)+1):if str1[j-1] == str2[i-1]:dp[i][j] = dp[i-1][j-1]else:dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1print(dp[len(str2)][len(str1)])
HJ55 挑7
题目链接:挑7_牛客题霸_牛客网
思路:遍历1-n(注意不包含0)之间的数,如果能整除7或者转换得到的字符串包含‘7’,计数加1,注意不能写两个if从句,以免重复计算。
代码
import sysn = int(sys.stdin.readline().strip())
count = 0
for num in range(1, n+1):num2str = str(num)if num%7 == 0 or '7' in num2str:count += 1
print(count)
HJ59 找出字符串中第一个只出现一次的字符
题目链接:找出字符串中第一个只出现一次的字符_牛客题霸_牛客网
思路:设置一个list,‘recorded’来储存暂时只出现过一次的字符,设置一个set,‘rep’ 存放重复的字符,遍历整个数组,如果它已经存在于recorded,从recorded中去除,并添加到rep中,如果recorded和rep中都没有当前字符,就添加到recorded中。
代码
import sys
str = sys.stdin.readline().strip()recorded = []
rep = set()
for s in str:if s in recorded:recorded.remove(s)rep.add(s) if s not in recorded and s not in rep:recorded.append(s)if recorded != []:print(recorded[0])
else:print(-1)
HJ63 DNA序列
题目链接:DNA序列_牛客题霸_牛客网
思路:首先想到的是从左至右依次找出长度为n的子串,如果CG个数比原来的大,就替换成新的。
我做了点剪枝操作:当我们计算完一个字符串后,会将原子串的位置向右平移一位的得到对应的新子串,它们中间字符保持不变,只有首位和末尾发生了变化,如果新的子字符串的末尾不是'C'或者'G',那么CG比例比起前一个子串,要么保持不变(原来子字符串的首位不是'C'或'G'),而且不是第一个有此CG比例的,要么减少(原来子字符串的首位是'C'或'G'),所以无需计算比较。因此,right指针不是每次都往右移一位,而是向右移到'C'或者'G'的位置,然后再计算新的CG比例,与之前的结果比较。
注意,为了省事,我统计的是CG的总个数,这道题输出的是子串,所以没问题,如果要输出CG比例,最后别忘了除以n。
代码
import sysstr1 = sys.stdin.readline().strip()
n = int(sys.stdin.readline().strip())
left, right = 0, n-1
ans = str1[left:right + 1]
count = ans.count('C') + ans.count('G')
while right <= len(str1) - 1:if str1[right] != 'C' and str1[right] != 'G':right += 1left = right - n + 1temp = str1[left:right+1]if temp.count('C') + temp.count('G') > count:ans = tempcount = temp.count('C') + temp.count('G')right += 1
print(ans)