leetcode —— 字串相關(28、344)

Inside_Zhang發表於2015-11-14

0. 字串搜尋

  • 28. Implement strStr()

    class Solution:
        def strStr(self, haystack, needle):
            """
            :type haystack: str
            :type needle: str
            :rtype: int
            """
            # return haystack.find(needle)
            if not needle:
                return 0
            n_haystack, n_needle = len(haystack), len(needle)
            for i in range(len(haystack)):
                if haystack[i:i+n_needle] == needle:
                    return i
            return -1
    

    使用 python 內建庫函式:

    class Solution:
        def strStr(self, haystack, needle):
            return haystack.find(needle)
    

1. 翻轉字串

  • 344. Reverse String

    class Solution:
        def reverseString(self, s):
            """
            :type s: str
            :rtype: str
            """
            arr = list(s)
            i, j = 0, len(arr)-1
            while i < j:
                arr[i], arr[j] = arr[j], arr[i]
                i += 1
                j -= 1
            return ''.join(arr)
    

相關文章