Python字符串类型在LeetCode中高频使用的方法

LeetCode高频使用的Python字符串方法

1. 基础但核心的字符串方法

str.split() – 字符串分割

# LeetCode 151. 反转字符串中的单词
def reverseWords(s: str) -> str:
    words = s.split()  # 默认按空格分割,自动处理多余空格
    return ' '.join(words[::-1])

# 用例
s = "  hello world  "
print(reverseWords(s))  # "world hello"

str.join() – 字符串连接

# LeetCode 28. 实现 strStr()
def strStr(haystack: str, needle: str) -> int:
    return haystack.find(needle)  # 内置方法一行解决

# 手动实现
def strStr_manual(haystack: str, needle: str) -> int:
    if not needle: return 0
    for i in range(len(haystack) - len(needle) + 1):
        if haystack[i:i+len(needle)] == needle:
            return i
    return -1

str.strip() – 去除首尾空格

# LeetCode 14. 最长公共前缀
def longestCommonPrefix(strs: list) -> str:
    if not strs: return ""
    
    prefix = strs[0]
    for s in strs[1:]:
        while not s.startswith(prefix):
            prefix = prefix[:-1]
            if not prefix: return ""
    return prefix

# 用例
strs = ["flower", "flow", "flight"]
print(longestCommonPrefix(strs))  # "fl"

2. 查找和验证方法

str.find() / str.index() – 查找子串

# LeetCode 28. 实现 strStr() def strStr(haystack: str, needle: str) -> int: return haystack.find(needle) # 内置方法一行解决 # 手动实现 def strStr_manual(haystack: str, needle: str) -> int: if not needle: return 0 for i in range(len(haystack) - len(needle) + 1): if haystack[i:i+len(needle)] == needle: return i return -1

str.startswith() / str.endswith() – 前缀后缀检查

# LeetCode 125. 验证回文串
def isPalindrome(s: str) -> bool:
    # 只思考字母数字字符,忽略大小写
    cleaned = ''.join(ch.lower() for ch in s if ch.isalnum())
    return cleaned == cleaned[::-1]

# 用例
s = "A man, a plan, a canal: Panama"
print(isPalindrome(s))  # True

str.isalnum() – 字母数字检查

# LeetCode 65. 有效数字(简化版)
def isNumber(s: str) -> bool:
    s = s.strip()
    if not s: return False
    
    # 检查是否包含数字
    has_digit = any(ch.isdigit() for ch in s)
    # ... 更复杂的数字验证逻辑
    return has_digit

str.isdigit() / str.isalpha()

# LeetCode 709. 转换成小写字母
def toLowerCase(s: str) -> str:
    return s.lower()  # 内置方法

# 手动实现
def toLowerCase_manual(s: str) -> str:
    result = []
    for ch in s:
        if 'A' <= ch <= 'Z':
            result.append(chr(ord(ch) + 32))
        else:
            result.append(ch)
    return ''.join(result)

4. 转换方法

str.lower() / str.upper() – 大小写转换

# LeetCode 709. 转换成小写字母 def toLowerCase(s: str) -> str: return s.lower() # 内置方法 # 手动实现 def toLowerCase_manual(s: str) -> str: result = [] for ch in s: if 'A' <= ch <= 'Z': result.append(chr(ord(ch) + 32)) else: result.append(ch) return ''.join(result)

str.replace() – 字符串替换

# LeetCode 替换空格
def replaceSpace(s: str) -> str:
    return s.replace(' ', '%20')

# 手动实现
def replaceSpace_manual(s: str) -> str:
    result = []
    for ch in s:
        if ch == ' ':
            result.append('%20')
        else:
            result.append(ch)
    return ''.join(result)

5. 字符串切片和索引的高级用法

# LeetCode 各种字符串反转问题
def reverseString(s: str) -> str:
    return s[::-1]  # 切片反转

def reversePrefix(word: str, ch: str) -> str:
    # LeetCode 2000. 反转单词前缀
    idx = word.find(ch)
    if idx == -1: return word
    return word[:idx+1][::-1] + word[idx+1:]

# 用例
print(reversePrefix("abcdefd", "d"))  # "dcbaefd"

LeetCode字符串题目的核心技巧

技巧1: 双指针技巧

# LeetCode 344. 反转字符串
def reverseString(s: list) -> None:
    left, right = 0, len(s) - 1
    while left < right:
        s[left], s[right] = s[right], s[left]
        left += 1
        right -= 1

# LeetCode 125. 验证回文串(双指针版)
def isPalindrome(s: str) -> bool:
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        
        if s[left].lower() != s[right].lower():
            return False
        
        left += 1
        right -= 1
    return True

技巧2: 滑动窗口

# LeetCode 3. 无重复字符的最长子串
def lengthOfLongestSubstring(s: str) -> int:
    char_set = set()
    left = 0
    max_length = 0
    
    for right in range(len(s)):
        while s[right] in char_set:
            char_set.remove(s[left])
            left += 1
        char_set.add(s[right])
        max_length = max(max_length, right - left + 1)
    
    return max_length

实战用例集合

# 综合用例展示
test_cases = [
    # 基础方法测试
    ("  hello  world  ", "split + join", "hello world"),
    ("Race a car", "回文检查", False),
    ("abcde", "find 'cd'", 2),
    
    # 转换测试
    ("Hello World", "小写转换", "hello world"),
    ("a b c", "空格替换", "a%20b%20c"),
    
    # 验证测试
    ("123abc", "isalnum", True),
    ("123", "isdigit", True),
    ("abc", "isalpha", True)
]

for input_str, operation, expected in test_cases:
    # 这里可以根据具体操作执行相应函数
    print(f"输入: '{input_str}' | 操作: {operation} | 预期: {expected}")

Python字符串类型在LeetCode中高频使用的方法

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容