1. 程式人生 > >Google面試題專題1 - leetcode14. Longest Common Prefix/20. Valid Parentheses/43. Multiply Strings

Google面試題專題1 - leetcode14. Longest Common Prefix/20. Valid Parentheses/43. Multiply Strings

leetcode14. Longest Common Prefix

題目描述

編寫函式,求陣列中字串的最長公共字首。如果沒有公共字首,返回空字串""。

例子
Example 1:

Input: [“flower”,“flow”,“flight”]
Output: “fl”

Example 2:

Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

思想
對給定字首的第i位,與所有字串的第i位進行比較。如果都相等,則繼續比較i+1位;否則,意味著發生了不全部相等的情況,return。

解法

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        
        pre = strs[0]
        for i in range(len(pre)):    # 對給定字首的每一位
            for s in strs[1:]:
                if
i >= len(s) or s[i] != pre[i]: return pre[:i] return pre

(小優化)

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        
        pre =
min(strs, key = len) for i, ch in enumerate(pre): for other in strs: if other[i] != ch: return pre[:i] return pre

20. Valid Parentheses

題目描述

給定只包含’(’, ‘)’, ‘{’, ‘}’, ‘[’ 和 ']'的字串,判斷該字串是否有效。
空字串也認為有效。

例子
Example 1:

Input: “()”
Output: true

Example 2:

Input: “()[]{}”
Output: true

Example 3:

Input: “(]”
Output: false

Example 4:

Input: “([)]”
Output: false

Example 5:

Input: “{[]}”
Output: true

思想
看到括號相關的題,想到棧。
左括號進棧,右括號判斷是否和棧頂的左括號匹配。若匹配,彈出棧頂左括號;否則,直接return False。最後判斷輔助棧是否為空。

解法

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        mapping = {')':'(', ']':'[', '}':'{'}
        stack = []
        for ch in s:
            if ch not in mapping:
                stack.append(ch)
            else:
                if not stack or stack.pop() != mapping[ch]:
                    return False
        return not stack

43. Multiply Strings

題目描述

給定兩個字串表示的非負整數num1和num2,返回num1和num2的乘積,也用字串表示。

num1和num2只包含數字0-9;num1和num2不包含前導零。

例子
Example 1:

Input: num1 = “2”, num2 = “3”
Output: “6”

Example 2:

Input: num1 = “123”, num2 = “456”
Output: “56088”

思想
首先自己模擬一下乘法運算過程:低位低位乘 ——> 高位高位乘。

  1. 固定num1的某一位x,與num2從低位到高位相乘(輔助的base2和carry);
  2. 從低到高遍歷num1的每一位(輔助base1)。

解法

class Solution(object):
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        num1 = num1[::-1]
        num2 = num2[::-1]
        
        res = 0
        base1 = 1
        for x in num1:
            x = ord(x) - 48
            
            summ = carry = 0
            base2 = 1
            for y in num2:
                y = ord(y) - 48
                
                pro = (x * y + carry) % 10
                carry = (x * y + carry) // 10
                
                summ += pro * base2
                base2 *= 10
            
            summ += carry * base2
            res += summ * base1
            base1 *= 10
        return str(res)