od机试算法题目,手打验证②

  1. HJ40-统计字符
while 1:
    try:
        s = input()
        words =0
        digits =0
        spaces =0
        others =0
        for i in s:
            if i.isalpha():
                words+=1
            elif i.isdigit():
                digits+=1
            elif i.isspace():
                spaces+=1
            else:
                others+=1
        print(words)
        print(spaces)
        print(digits)
        print(others)


    except:
        break
  1. HJ101-输入整型数组和排序标识,对其元素按照升序或降序进行排序
while 1:
    try:
        n = int(input())
        s = list(map(int, input().strip().split()))

        sort_num = input()
        sort_s =[]

        if sort_num == '0':
            s.sort()
        else:
            s.sort(reverse=True)
        print(*s)

    except:
        break

  1. HJ8-合并表
#数据表记录包含表索引index和数值value(int范围的正整数),
# 请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。


num = int(input())
dic = {}
for i in range(num):
    line = input().split()
    key = int(line[0])
    value = int(line[1])
    dic[key] = dic.get(key,0) + value
for key in sorted(dic):
    print(key,dic.get(key))
  1. HJ14-字符串排序

'''
给定 n 个字符串,请对 n 个字符串按照字典序排列。

数据范围: 1 \le n \le 1000 \1≤n≤1000  ,字符串长度满足 1 \le len \le 100 \1≤len≤100 

'''
import sys

try:
    lst = []
    n = int(input())
    for s in range(n):
        line_s = input()
        lst.append(line_s)
    lst = sorted(lst)
    for i in lst:
        print(i)

except:
    pass
  1. HJ27-查找兄弟单词

while True:
    try:
        pass
        s_input = input().split()
        n = int(s_input[0])
        dict = s_input[1:n+1]
        print(dict)
        print(type(dict))
        s = s_input[-2]
        k = int(s_input[-1])
        temp = []

        for i in dict:
            if len(i) == len(s) and i != s and sorted(i) == sorted(s):
                temp.append(i)

        print(temp)
        print(len(temp))
        if k<= len(temp):
            print(sorted(temp)[k-1])

    except:
        break

  1. HJ68-成绩排序
# 给定一些同学的信息(名字,成绩)序列,请你将他们的信息按照成绩从高到低或从低到高的排列,相同成绩
#
# 都按先录入排列在前的规则处理。


while 1:
    try:
        n = int(input())
        sort_type = input()
        student = []
        for i in range(n):
            info = input().split()
            student.append([info[0], int(info[1])])
        if sort_type == "0":
            student = sorted(student, key=lambda x: x[1], reverse=True)
        else:
            student = sorted(student, key=lambda x: x[1])
        for i in range(n):
            print(student[i][0], student[i][1])
    except:
        break
  1. NC37-合并区间
'''
给出一组区间,请合并所有重叠的区间。
请保证合并后的区间按区间起点升序排列。

输入:
[[10,30],[20,60],[80,100],[150,180]]
复制
返回值:
[[10,60],[80,100],[150,180]]

'''
class Solution:
    def merge(self , intervals ):
        if not intervals:
            return []
        intervals.sort(key=lambda x:x.start)
        res = [intervals[0]]
        for i in intervals[1:]:
            if res[-1].end<i.start:
                res.append(i)
            elif res[-1].end<i.end:
                res[-1].end=i.end
        return res
  1. leetcode1614-括号的最大嵌套深度
class Solution:
    def maxDepth(self, s: str):
        n = 0
        num = []
        for i in s:
            if i =='(':
                n+=1
            elif i ==')':
                n-=1
            num.append(n)
        return max(num)
  1. NC52-有效括号排序
'''
给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
'''

class Solution:
    def isValid(self , s: str) -> bool:
        # write code here
        if len(s) % 2 ==1:
            return False
        while '{}' in s or '()' in s or '[]' in s:
            s = s.replace('{}','').replace('()','').replace('[]','')
        if s =='':
            return True
        else:
            return False
  1. leetcode面试题 08.08. 有重复字符串的排列组合
import itertools
from itertools import permutations
class Solution:
    def permutation(self, S):
        tmp = []
        for i in set(itertools.permutations(S)):
            tmp.append(''.join(i))
        return tmp
  1. leetcode674-最长连续子序列
nums = list(map(int,input().split()))
print(nums)
size = len(nums)
print(size)
dp = [1 for _ in range(size)]
print('初始dp', dp)
for i in range(1, size):
    if nums[i - 1] < nums[i]:
        dp[i] = dp[i - 1] + 1

print(max(dp))

  1. NC17-最长回文子串
class Solution:
    def getLongestPalindrome(self , A: str) -> int:
        if len(A) == 1:
            return 1
        ret = 0
        cycle = [1 for _ in A]
        for i in range(1, len(A)):
            l1 = cycle[i - 1]
            if l1 == 1 and A[i-1] == A[i]:
                cycle[i] = l1 + 1
            elif l1 - cycle[i - 2] == 1 and A[i] == A[i-1]:
                cycle[i] = l1 + 1
            elif i-l1 > 0 and A[i] == A[i-l1-1]:
                cycle[i] = l1 + 2
            elif i > 1 and A[i] == A[i-2]:
                cycle[i] = 3
            ret  = max(ret, cycle[i])
        return ret
  1. HJ41-称砝码
'''
现有n种砝码,重量互不相等,分别为 m1,m2,m3…mn ;
每种砝码对应的数量为 x1,x2,x3...xn 。现在要用这些砝码去称物体的重量(放在同一侧),问能称出多少种不同的重量。
注:称重重量包括 0
'''
# 对于每组测试数据:
# 第一行:n --- 砝码的种数(范围[1,10])
# 第二行:m1 m2 m3 ... mn --- 每种砝码的重量(范围[1,2000])
# 第三行:x1 x2 x3 .... xn --- 每种砝码对应的数量(范围[1,10])
# n = int(input())
# m = list(map(int, input().split()))
# x = list(map(int, input().split()))
while True:
    try:
        n = int(input())
        m = input().split(" ")
        x = input().split(" ")

        # mx为所有砝码,比如示例mx为[1, 1, 2]
        mx, l = [], {0}
        for i in range(n):

            mx.extend([int(m[i])] * int(x[i]))

        for i in mx:
            # 每次加一块砝码,使用union(并集)得到新去重的组合,如果不使用union则稍微麻烦一点,需要考虑循环中改变set
            for j in l:
                l = l.union({i + j})
        print(len(l))
    except:
        break

  1. 剑指offer32-从上到下打印二叉树-广度优先
'''
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
'''

import collections

class Solution:
    def levelOrder(self, root):
        if not root:
            return []
        res, queue = [], collections.deque()
        queue.append(root)
        while queue:
            node = queue.popleft()
            res.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return res

  1. 剑指offer32-从上到下每一层打印到一行-广度优先
import collections
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root):
        if not root:
            return []
        res, queue = [], collections.deque()
        queue.append(root)
        while queue:
            # 创建个临时列表
            tmp = []
            for num in range(len(queue)):
                node = queue.popleft()
                tmp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

            res.append(tmp)
        return res

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值