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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值