二刷 leetcode (6)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ANNILingMo/article/details/80965157

242有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false

说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

代码:

class Solution4:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        #### the first method
        # s = sorted(s)
        # t = sorted(t)
        # if s == t:
        #     return True
        # else:
        #     return False

        ####  the second method
        # from collections import Counter
        # dic_t = Counter(t)
        # dic_s = Counter(s)
        # if len(dic_s) != len(dic_t):
        #     return False
        # for key, value in dic_s.items():
        #     if key in dic_t and value == dic_t[key]:
        #         continue
        #     else:
        #         return False
        # return True

        #### the third method
        from string import ascii_lowercase
        for c in ascii_lowercase:
            if s.count(c) != t.count(c):
                return False
        else:
            return True

s = Solution4()
print(s.isAnagram(s = "rat", t = "car"))

125验证回文串

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:

输入: "race a car"
输出: false
代码:
class Solution5:
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        #### 运用python string 模块的特性
        # from string import punctuation
        # s = s.strip().lower()
        # # print(s)
        # for punc in punctuation:
        #     s = s.replace(punc, '')
        # s = s.replace(' ', '')
        # print(s)
        # return s == s[::-1]

        #### the second method
        ### isalnum():方法检测字符串是否由字母和数字组成; 返回类型是boolean类型
        s = list(filter(str.isalnum, s.lower()))
        return s == s[::-1]

s = Solution5()
print(s.isPalindrome( "A man, a plan, a canal: Panama"))
8 字符串转整数 (atoi)

实现 atoi,将字符串转为整数。

在找到第一个非空字符之前,需要移除掉字符串中的空格字符。如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字符即为整数的值。如果第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。

字符串可以在形成整数的字符后面包括多余的字符,这些字符可以被忽略,它们对于函数没有影响。

当字符串中的第一个非空字符序列不是个有效的整数;或字符串为空;或字符串仅包含空白字符时,则不进行转换。

若函数不能执行有效的转换,返回 0。

说明:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。如果数值超过可表示的范围,则返回  INT_MAX (231 − 1) 或 INT_MIN (−231) 。

示例 1:

输入: "42"
输出: 42

示例 2:

输入: "   -42"
输出: -42
解释: 第一个非空白字符为 '-', 它是一个负号。
     我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。

示例 3:

输入: "4193 with words"
输出: 4193
解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。

示例 4:

输入: "words and 987"
输出: 0
解释: 第一个非空字符是 'w', 但它不是数字或正、负号。
     因此无法执行有效的转换。

示例 5:

输入: "-91283472332"
输出: -2147483648
解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 
     因此返回 INT_MIN (−231) 。
代码:
class Solution:
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
       
    
        ### the first method
        import re
        reg = re.findall(r"^[\-\+]?\d+", str.strip())
        if len(reg) != 0:
            chars = reg[0]
            if chars[0] =="-" or chars[0] =="+":
                temp = chars[1:]
            else:
                temp = chars[:]
            res = int(temp)
            if chars[0] == '-':
                return -res if res <= 2**31 else -2**31
            else:
                return res if res <  2**31 else 2**31 -1
        else:
            return 0
        
        ####  the second method
        # if len(str) == 0:
        #     return 0
        # list_str = list(str.strip())
        # if list_str[0] == '-':
        #     sign = -1
        # else:
        #     sign = 1
        # if list_str[0] in ['-','+']:
        #     del list_str[0]
        # i, res = 0, 0
        # while i < len(list_str) and list_str[i].isdigit():
        #     res = res * 10 + ord(list_str[i]) - ord('0')
        #     i += 1
        # return max(-2**31, min(sign * res, 2**31 -1))
        



猜你喜欢

转载自blog.csdn.net/ANNILingMo/article/details/80965157