LeetCode探索模块初级算法字符串章节python3代码实现

声明:本人刚刚入门,算法能力欠佳,所写算法不是最优算法,只提供使用python3的读者以参考。

反转字符串

class Solution:
    def reverseString(self, s):
        """ :type s: str :rtype: str """
        return s[::-1]

颠倒整数

class Solution:
    def reverse(self, x):
        """ :type x: int :rtype: int """
        if x>=0:
            s = str(x)[::-1]
            num = int(s)
        else:
            s = str(x)[:-len(str(x)):-1]
            num = -int(s)
        if num>2**31-1 or num<-2**31:
            return 0
        return num

字符串中的第一个唯一字符

class Solution:
    def firstUniqChar(self, s):
        """ :type s: str :rtype: int """
        dic = {}
        l = []
        for i in range(len(s)):
            if s[i] not in l:
                if s[i] not in dic.keys():
                    dic[s[i]] = i
                else:
                    l.append(s[i])
                    dic.pop(s[i])
        res = list(dic.values())
        if len(res) != 0:
            return min(res)
        else:
            return -1

有效的字母异位词

class Solution:
    def isAnagram(self, s, t):
        """ :type s: str :type t: str :rtype: bool """
        from collections import Counter
        if(Counter(s)==Counter(t)):
            return True
        else:
            return False

验证回文字符串

class Solution:
    def isPalindrome(self, s):
        """ :type s: str :rtype: bool """
        s1 = s.lower()
        l = []
        for i in s1:
            if 'a' <= i <= 'z' or '0' <= i <= '9':
                l.append(i)
        le = len(l)
        for j in range(le//2):
            if l[j] != l[-j-1]:
                return False
        return True

字符串转整数(atoi)

class Solution:
    def myAtoi(self, str):
        """ :type str: str :rtype: int """
        str = str.lstrip(' ')
        if len(str)>0:
            flag = 1
            if str[0] == '+':
                str = str[1:]
            elif str[0] == '-':
                str = str[1:]
                flag = -1
            elif '0' <= str[0] <= '9':
                pass
            else:
                return 0

            new_s = ""
            for s in str:
                if '0' <= s <= '9':
                    new_s += s
                else:
                    break
            if len(new_s)>0:
                if flag == -1:
                    n = -int(new_s)
                    if n >= -2**31:
                        return n
                    else:
                        return -2**31
                else:
                    n = int(new_s)
                    if n <= 2**31-1:
                        return n
                    else:
                        return 2**31-1
            else:
                return 0
        return 0

实现strStr()

class Solution:
    def strStr(self, haystack, needle):
        """ :type haystack: str :type needle: str :rtype: int """
        return haystack.find(needle)

数数并说

class Solution:
    def countAndSay(self, n):
        """ :type n: int :rtype: str """
        if n == 1:
            return "1"
        elif n == 2:
            return "11"
        elif n > 2:
            pre = self.countAndSay(n-1)
            string = ""
            count = 1
            for i in range(1,len(pre)):
                if pre[i] != pre[i-1]:
                    string = string + str(count) + pre[i-1]
                    count = 1
                else:
                    count += 1
            string = string + str(count) + pre[i]
            return string

最长公共前缀

class Solution:
    def longestCommonPrefix(self, strs):
        """ :type strs: List[str] :rtype: str """
        l = len(strs)
        if l > 0:
            le = len(strs[0])
            for string in strs:
                le_new = len(string)
                if le_new < le:
                    le = le_new
            for i in range(le):  # i表示一个字符串的第几个字符
                for j in range(1, l):  # j表示第几个字符串
                    if strs[j][i] != strs[j - 1][i]:
                        num = i
                        if num > 0:
                            return strs[0][:num]
                        else:
                            return ""
            num = le
            if num > 0:
                return strs[0][:num]
            else:
                return ""
        else:
            return ""     
点赞