欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

辣鸡刘的Leetcode之旅2【最长公共前缀,有效的括号,合并链表,删除排序数组中的重复项】

程序员文章站 2024-02-24 22:56:04
...

1.最长公共前缀

问题描述:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ” “.
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。

举例:

Input: ["flower","flow","flight"]
Output: "fl"

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
import re
class Solution:
    def longestCommonPrefix(self,strs):
        if not strs or strs[0] == '':
            return ''
        prefix = strs[0]
        for i in range(1, len(strs)):
            match = re.match(prefix, strs[i])
            while not match:
                prefix = prefix[:-1]
                match = re.match(prefix, strs[i])
        return prefix

2. 有效的括号

题目描述:
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
举例:

示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true

代码如下:这个也是大神的思路,我做的太繁琐,不想引起误导

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dict = {']': '[', '}': '{', ')': '('}
        stack=[]
        for char in s:
            if char in dict.values():
                stack.append(char)
            elif char in dict.keys():
                if stack==[] or dict[char]!=stack.pop():
                    return False
            else:
                return False
        return stack==[]

3. 合并链表

题目描述:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
举例:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

这个题用到了链表操作,辣鸡刘做不出来,以下是大神的解法,超级简单,实力的体现:

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        res = []
        while l1 != None:
            res.append(l1.val)
            l1 = l1.next
        while l2 != None:
            res.append(l2.val)
            l2 = l2.next
        return sorted(res)

4.删除排序数组中的重复项

题目描述:
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
举例:

Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.

这个题我起初想用list(set(nums))直接得到无重复序列,然后利用len()函数求解长度,结果可想而知,是我想太多,哈哈

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = 1
        while n < len(nums):
            if nums[n] == nums[n-1]:
                del(nums[n])
            else:
                n += 1
        return len(nums)

附上大神的代码:

nums[:]= sorted(list(set(nums)))
        return len(nums)

牛皮!

相关标签: 最长公共前缀