辣雞劉的Leetcode之旅2【最長公共前綴,有效的括號,合併鏈表,刪除排序數組中的重複項】

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)

牛皮!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章