LeetCode String算法题(Easy级别)整理 Part 1

28. Implement strStr()

题目简介:实现strStr()函数的功能。

解题思路:此题意义不大,直接调用string.find()即可。代码如下:

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

38. Count and Say

题目简介:
Count and Say

解题思路:类似于杨辉三角的求解方式。代码如下:

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n <= 0:
            return ""
        ary = ['1','11','21','1211','111221']
        if n < 6:
            return ary[n-1]
        t1 = ary[4]
        t2 = ''
        for i in xrange(5,n):
            count = 0
            cur = t1[0]
            t2 = ''
            for j in xrange(len(t1)):
                if t1[j] == cur:
                    count+=1
                else:
                    t2+=(str(count)+cur)
                    cur = t1[j]
                    count = 1
            t2+=(str(count)+cur)
            t1 = t2
        return t1

58. Length of Last Word

题目简介:求一个句子的最后一个单词的长度。

解题思路:分词后求解即可。代码如下:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        slist = s.split()
        if not slist:
            return 0
        return len(slist[-1])

344. Reverse String

题目简介:将字符串反转

解题思路:简单得很,直接上代码:

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

345. Reverse Vowels of a String

题目简介:讲一个字符串中的所有元音字母进行反转,其余字符不变。

解题思路:从两边向中间聚拢,依次判断当前字符是否是元音字母,是的话则互换。代码如下:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = list(s)
        vowels = 'aeiouAEIOU'
        left = 0
        right = len(s)-1
        while left < right:
            while s[left] not in vowels and left < right:
                left+=1
            while s[right] not in vowels and left < right:
                right-=1
            s[left],s[right] = s[right],s[left]
            left+=1
            right-=1
        return ''.join(s)

383. Ransom Note

题目简介:判断一封勒索信上的字符是否能从给定的杂志上全部获得。每个字符只能用一次。

解题思路:先将勒索信上的字符和出现个数保存至字典中,然后依次判断各字符是否能在magazine中获得以及个数要求是否满足。代码如下:

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        dr = {}
        for c in ransomNote:
            if dr.has_key(c):
                dr[c]+=1
            else:
                dr[c] = 1
        for k,v in dr.items():
            if k not in magazine or magazine.count(k) < v:
                return False
        return True

434. Number of Segments in a String

题目简介:找出一个字符串中的段数,一段为一串不含不可打印字符的连续字符。

解题思路:直接分隔字符串即可。代码如下:

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        return len(s.split())

443. String Compression

题目简介:压缩字符串,压缩规则详见leetcode

解题思路:一轮遍历,依次判断相应字符应采取的操作即可。代码如下:

class Solution(object):
    def compress(self, chars):
        """
        :type chars: List[str]
        :rtype: int
        """
        cur = None
        length = 0
        count = 0
        for c in chars:
            if cur != c:
                if cur != None:
                    chars[length] = cur
                    length+=1
                    if count > 1:
                        s = str(count)
                        for x in s:
                            chars[length] = x
                            length+=1
                cur = c
                count=1
            else:
                count+=1
        if cur != None:
            chars[length] = cur
            length+=1
            if count > 1:
                s = str(count)
                for x in s:
                    chars[length] = x
                    length+=1
        return length

520. Detect Capital

题目简介:给定某个单词,判断单词的大写字母的用法是否正确,正确的用法说明见leetcode

解题思路:一轮遍历,根据规则遍历即可。代码如下:

class Solution(object):
    def detectCapitalUse(self, word):
        """
        :type word: str
        :rtype: bool
        """
        if not word:
            return True
        l = len(word)
        if 'A' <= word[0] and word[0] <= 'Z':
            count = 1
            for i in xrange(1,l):
                if 'A' <= word[i] and word[i] <= 'Z':
                    count+=1
            if count == 1 or count == l:
                return True
            return False
        else:
            count = 0
            for i in xrange(1,l):
                if 'A' <= word[i] and word[i] <= 'Z':
                    count+=1
            if count == 0:
                return True
            return False            

521. Longest Uncommon Subsequence I

题目简介:给定两个字符串,判断最大不同子串的长度。

解题思路:认为这是道差题的人比认为其是好题的人多很多很多= =原因的话看了代码大家应该也就了解了= =

class Solution(object):
    def findLUSlength(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: int
        """
        if a == b:
            return -1
        else:
            return max(len(a),len(b))

541. Reverse String II

题目简介:按照规则反转字符串。

解题思路:代码如下:

class Solution(object):
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        l = len(s)
        s = list(s)
        for i in xrange(0,l,2*k):
            if l-i < k:
                s[i:] = s[i:][::-1]
            else:
                s[i:i+k] = reversed(s[i:i+k])
        return "".join(s)

551. Student Attendance Record I

题目简介:根据出勤记录判断学生是否可受奖励。

解题思路:代码如下:

class Solution(object):
    def checkRecord(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if s.count('A') > 1 or 'LLL' in s:
            return False
        return True

557. Reverse Words in a String III

题目简介:给定字符串,保证字符串中的各单词相对位置不变,但是各单词内的字符都进行反转。

解题思路:字符串分割后,反转再重新组合即可。代码如下:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        l = s.split()
        l2 = []
        for i in range(len(l)):
            l2.append("".join(list(reversed(l[i]))))
        return " ".join(l2)

657. Judge Route Circle

题目简介:根据机器人的移动轨迹,判断其最后是否能回到原点。

解题思路:只要往上和往下的移动与往左和往右的移动分别抵消,即可回到原点。代码如下:

class Solution(object):
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R')

680. Valid Palindrome II

题目简介:给定一串字符串,判断能否通过删除最多一个字符,生成回文串

解题思路:先判断本身是否为回文串,若是,直接返回True;否则,从两端开始对比,若出现不一致且可通过删除一个字符形成回文,只存在两种可能的删法,依次判断即可。其他情况则都为False。代码如下:

class Solution(object):
    def validPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        rev = s[::-1]
        if s == rev: return True
        l = len(s)
        for i in xrange(l):
            if s[i] != rev[i]:
                return s[i:l-i-1] == rev[i+1:l-i] or rev[i:l-i-1] == s[i+1:l-i]
        return False

686. Repeated String Match

题目简介:给定字符串A和B,求A重复若干次,是否能包含B,即让B编程AA…A的子串。

解题思路:首先可判断明显不可能的情况,即B中有A中不存在的字符;其次,找出符合最小长度要求的k,满足条件的只可能是k或k+1倍A。代码如下:

class Solution(object):
    def repeatedStringMatch(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: int
        """
        if len(set(B)) > len(set(A)):
            return -1
        if len(B)%len(A) == 0:
            k = int(len(B)/len(A))
        else:
            k = int(len(B)/len(A))+1
        if B in A * k: 
            return k
        elif B in A * (k + 1): 
            return k + 1
        return -1

696. Count Binary Substrings

题目简介:给定一串01字串,求符合
特定要求的子串的个数。

解题思路:一轮遍历,依次判断即可。代码如下:

class Solution(object):
    def countBinarySubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        l = len(s)
        if l < 2:
            return 0
        i1 = 0
        i2 = 0
        count = 0
        times = 0
        for i in range(l):
            if i == 0:
                i2 = 1
                continue
            if s[i-1] != s[i]:
                times+=1
                if times > 1:
                    count+=min(i1,i2)
                i1=i2
                i2=1
            else:
                i2+=1
        times+=1
        if times > 1:
            count+=min(i1,i2)
        return count
点赞