刷题小记--字符串

1.CF#Codeforces Round 854 by cybercats (Div. 1 + Div. 2)–C题
题目大意:
给出一个字符串,求这个字符串要如何排序可以使得排序后的字符串的正序和逆序中最大的值最小。比如给出字符串s = aab,对s的排序可以是:
s1 = aab : smax=max(aab,baa)=baa
s2 = aba : smax=max(aba,aba)=aba
s3 = baa : smax=max(baa,aab)=baa
当 s = aba,得到 min(smax)

N = int(input())
for i in range(N):
    s = list(input())
    s=sorted(s)
    L,R,c,l = "","",0,len(s)
    while c < l-1:
        if s[c] == s[c+1]:#有重复字符串就放在目标字符串的首和尾
            L += s[c]
            R += s[c+1]
            c += 2
            continue
        if s[c+1] == s[l-1]:#将相同的字符串移动到当前和当前的下一个
            s[c],s[l+c>>1] = s[l+c>>1],s[c]
        else:#没有相同字符串则直接加入
            R += s[c]
            c += 1
        break
    print(L+"".join(s[c:])+R[::-1])


2.CF#Codeforces Round 767 (Div. 1)–B题
题目大意:
给出n个字符串(每个字符串的长度不超过3),可以对这些字符串进行删除,但不能更改顺序,问能否实现:使这些字符串组成回文

N = int(input())
for i in range(N):
    n = int(input())
    nums = []
    for _ in range(n):
        nums.append(input())
    pre = set()#记录已经审查过的字符串
    next = set()#记录可以和已经审查过的字符串组成回文的字符串
    for s in nums:
        l = len(s)
        if l == 1:#对于长度为1的字符串直接实现回文
            print("YES")
            break
        if l == 2:#对于长度为2的字符串,先看它本身是否回文,再看能否和之前的组成回文
            tmp = s[::-1]
            if tmp == s or tmp in pre or tmp in next:
                print("YES")
                break
        if l == 3:#同长度为2的字符串,不同的是需要将字符串前两位存入next(如果后续与s[:2]回文就可以
            next.add(s[:2])
            if s == s[::-1] or s[::-1] in pre or s[2] + s[1] in pre:
                print("YES")
                break
        pre.add(s)
    else:
        print("NO")


3.CF#Codeforces Beta Round 93 (Div. 1 Only)–B题
题目大意:
输入一个字符串查找一个这样的子串:出现在字符串的开头、结尾和中间,如果有多个取最长的

def build_table(s):#建造KMP表格
    table = [0] * len(s)
    j = 0
    for i in range(1, len(s)):
        while j > 0 and s[i] != s[j]:
            j = table[j - 1]
        if s[i] == s[j]:
            j += 1
        table[i] = j
    return table

s = input()
table = build_table(s)
n = len(s)
if table[-1] == 0:
    print("Just a legend")
else:
    ll = table[-1]
    for i in range(n - 1):#至少要有3个重复子串
        if table[i] == ll:
            print(s[:ll])
            break
    else:
        if table[ll - 1] == 0:
            print("Just a legend")
        else:
            print(s[:table[ll - 1]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值