Implement strStr()

Implement strStr()

给定两个字符串strA / strB,计算后者在前者第一次出现的首字母位置(javaindexOf()CstrStr()

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        if haystack == needle:
            return 0

        for i in range(len(haystack)):
            subStr = ''.join(haystack[i : i + len(needle)])
            if len(needle) > len(subStr): #在输入的两个字符很长的情况下,有可能存在资源消耗过大,因此先用长度做简单判断
                return -1

            if subStr == needle:
                return i
        return  -1

Solution for Remove Duplicates from Sorted Array

题目要求不使用额外的空间进行去重,并且不要求指定长度后的数组元素结果

解决方案:把指针前面的子集可以作为新的数组使用即可

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        if len(nums) < 2:
            return 1
        
        index = 0
        for i in range(1, len(nums)):
            if nums[i] != nums[index]:
                index = index + 1
                nums[index] = nums[i]

        return index + 1

Solution for Merge Two Sorted Lists

Merge Two Sorted Lists

问题是两个单向有序链表A / B合并,解题思路有两个

  • 递归

比较AB的第一个元素a1 / b1,假设a1 < b1,那么A.nextB先合并,合并后的第一个链表节点赋值给A.next,反之亦然,直到两个链表其中一个完成遍历,将剩余的节点挂在最后一个合并节点上即可完成合并

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1:
            return l2
        if not l2:
            return l1
        if l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

Solution for Valid Parentheses

Valid Parentheses

  • 使用栈匹配括号

通过栈这种数据结构可以很好的解决符号匹配问题:

  1. 判定栈顶元素是否和当前元素匹配,例如'('')'匹配
  2. 如果匹配那么pop,如果不匹配那么append
  3. 最后查看栈的长度是否为0

当输入字符串的长度无法被2整除时,可以判定一定不是正确的字符串

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        matchPairs = {
            '(':')',
            '[':']',
            '{':'}',
            ')':'(',
            ']':'[',
            '}':'{'}

        stack = []
        if len(s) % 2 != 0:
            return False
        
        for char in s:
            if stack and matchPairs[stack[-1]] == char:
                stack.pop()
            else:
                stack.append(char)
        
        return 0 == len(stack)

Solution for Roman to Integer

Roman to Integer

  • 倒序遍历求值

罗马数字存在以下特征:

key value
I 1
IV 4
V 5
IX 9
X 10
XL 40
L 50
XC 90
C 100
CD 400
D 500
CM 900
M 1000