leetcode traning_string(2)

本文介绍了如何在Python中实现字符串的反转及验证回文特性,并探讨了寻找最长回文子串的有效算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Reverse Words in a String



Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".


def reverse(s):
    if s is None: return None
    a=[]
    b=[]
    c=""
    for i in range(len(s)):
        if s[i]==' ': 
            a.append(i)
    if a[0]==0:
        for j in range(len(a)):
            b.append(s[a[j]:a[j+1]])
    else:
	b.append(s[:a[0]])
        for j in range(len(a)-1):
            b.append(s[a[j]:a[j+1]])
        b.append(s[a[-1]:])
    b=b[::-1]
    d=b[-1]
    b[-1]=' '
    b.append(d)
    for i in range(len(b)):
        c+=b[i]
    return c
        
Notes:

1.the thinking itself is not complex, when I draw them on paper. The sky is blue_3 7 10_'the' ' sky' ' is' ' blue'_reverse

2.one important thing is needed to pay attention to. When we refer to slice, the last one will not be taken into consederation.


Valid Palindrome

Given a string, determine if it is a palindrome,
considering only alphanumeric characters and ignoring cases.

Example
"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.
Note
Have you consider that the string might be empty?
This is a good question to ask during an interview.
For the purpose of this problem,
we define empty string as valid palindrome.

Challenge
O(n) time without extra memory.

#signal to '';str.lower();reverse and compare
def palindrome(s):
    signal=(',','.',':',';',' ','?')
    for i in range(len(signal)):
        s=s.replace(signal[i],"")
    s=str.lower(s)
    reverse=s[::-1]
    return s==reverse
Notes:

1.Null signal is "",not '';

2.string is an important part in code; str.lower() s.replace() should be remembered.

class Solution:
    # @param {string} s A string
    # @return {boolean} Whether the string is a valid palindrome
    def isPalindrome(self, s):
        if not s:
            return True

        l, r = 0, len(s) - 1

        while l < r:
            # find left alphanumeric character
            if not s[l].isalnum():
                l += 1
                continue
            # find right alphanumeric character
            if not s[r].isalnum():
                r -= 1
                continue
            # case insensitive compare
            if s[l].lower() == s[r].lower():
                l += 1
                r -= 1
            else:
                return False
        #
        return True

##functions learning:Python isalnum() 方法检测字符串是否由字母和数字组成。

两步走:

  1. 找到最左边和最右边的第一个合法字符(字母或者字符)
  2. 一致转换为小写进行比较
## isalnum() to find the formal character is more general.

Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000,
and there exists one unique longest palindromic substring.

Example
Given the string = "abcdzdcab", return "cdzdc".
Challenge
O(n2) time is acceptable. Can you do it in O(n) time.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值