每日一题:字符串(面试题)

本文介绍了四个关于字符串处理的面试题目,包括判断字符唯一性、检查字符串是否为字符重排、URL编码以及字符串压缩。提供了详细的解题代码,如通过字典检查字符唯一性,对字符串排序判断重排,使用replace方法实现URL编码,以及双指针法压缩字符串。这些题目涵盖了字符串的基本操作和算法应用。
摘要由CSDN通过智能技术生成

面试题 01.01. 判定字符是否唯一

链接:https://leetcode-cn.com/problems/is-unique-lcci/

def isUnique(astr: str) -> bool:
    dic = {}
    for s in astr:
        if s not in dic.keys():
            dic[s] = 1
        else:
            dic[s] += 1
    for v in dic.values():
        if v > 1: return False

    return True

面试题 01.02. 判定是否互为字符重排

链接:https://leetcode-cn.com/problems/check-permutation-lcci/

def CheckPermutation(s1: str, s2: str) -> bool:
    s1 = list(s1)
    s1.sort()
    s2 = list(s2)
    s2.sort()

    if s1 == s2: return True
    else: return False

s1="abc"
s2="bad"
print(CheckPermutation(s1,s2))

面试题 01.03. URL化

链接:https://leetcode-cn.com/problems/string-to-url-lcci/

def replaceSpaces(S: str, length: int) -> str:
    '''利用 replace 进行替换'''
    return S[:length].replace(" ", "%20")

面试题 01.06. 字符串压缩

链接:https://leetcode-cn.com/problems/compress-string-lcci/

def compressString(S: str) -> str:
    '''双指针'''
    if len(S)==0:return S
    i = 0
    j = 0
    ans = ''
    for j in range(len(S)):
        if S[j] != S[i]:
            ans = ans + S[i] + str(j-i)
            i = j
    ans = ans + S[i] + str(j-i+1)
    return S if len(ans) >= len(S) else ans

S = "aabcccccaaa"
print(compressString(S))

面试题 01.09. 字符串轮转

链接:https://leetcode-cn.com/problems/string-rotation-lcci/

def isFlipedString(s1: str, s2: str) -> bool:
    '''
    如果一个字符串是另一个字符串的旋转,那么它就是在某个特定点上的旋转。
    例,字符串waterbottle在3处的旋转意味着在第三个字符处切割waterbottle,
    并在左半部分(wat)之前放置右半部分(erbottle)。
    '''
    if len(s1) != len(s2): return False
    if len(s1) == len(s2) == 0: return True
    for i in range(0, len(s1)):
        a = s1[:i]
        b = s1[i:]
        ans = b + a
        if ans == s2: return True
    else:
        return False

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值