牛客刷题 | HJ45 名字的漂亮度,HJ48 从单向链表中删除指定值的节点

HJ45 名字的漂亮度

题目链接:名字的漂亮度_牛客题霸_牛客网 (nowcoder.com)

思路:统计单词中每个字母出现的次数,依次按出现频率从大到小分配漂亮度。

代码

import sys

n = int(sys.stdin.readline().strip())
strings = []
for i in range(n):
    strings.append(sys.stdin.readline().strip())

def beauty(s):
    dic = dict()
    for i in s:
        if i in dic:
            dic[i] = dic.get(i) + 1
        else:
            dic[i] = 1
    n = len(dic)
    lis = sorted(dic.values(), reverse = True)
    ans = 0
    for i in range(n):
        ans += (26 - i) *lis[i]
    return ans
for s in strings:
    print(beauty(s))

HJ48 从单向链表中删除指定值的节点

题目链接:从单向链表中删除指定值的节点_牛客题霸_牛客网 (nowcoder.com)

思路:这道题整合了链表的定义、链表节点的插入和删除。需要比较的是node的值和要找的val,一定是node.val == val1 而不是node==val1,一个节点是不会等于一个值的!

import sys

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None

def insert(head, val1, val2):
    cur = head
    while cur:
        preNext = cur.next
        if cur.val == val2:
            cur.next = ListNode(val1)
            cur.next.next = preNext           
            break
        else:
            cur = cur.next
    return head

def delete(head, val):
    dummy_head = ListNode(val = None)
    dummy_head.next = head
    cur = dummy_head
    while cur.next:
        if cur.next.val == val:
            cur.next = cur.next.next
            break
        else:
            cur = cur.next
    return dummy_head.next

lis = list(map(int,sys.stdin.readline().strip().split()))
n = lis[0]
head = lis[1]
node = lis[2:-1]
deleted = lis[-1]


head = ListNode(head)
left, right = 0, 1
while right < len(node):
    insert(head, node[left], node[right])
    left += 2
    right += 2
    


delete(head, deleted)
ans = []
cur = head
while cur:
    ans.append(str(cur.val))
    cur = cur.next
print(' '.join(ans))




    

HJ50 四则运算

 题目链接:四则运算_牛客题霸_牛客网 (nowcoder.com)

思路:犯规了,用了replace和eval函数,将字符表示式直接转变为数学运算。不用这两个函数应该是用栈,有空了尝试一下。

代码

import sys
inp = sys.stdin.readline().strip()

inp = inp.replace('[', '(')
inp = inp.replace('{', '(')
inp = inp.replace(']', ')')
inp = inp.replace('}', ')')
          
print(eval(inp))

你可能感兴趣的:(笔试刷题,python,开发语言)