leetcode 腾讯 2018 秋招精选(50 题)Easy Part (5)

20. 有效的括号

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

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

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

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

思路:使用栈的性质来解。遍历字符串,若字符串是'{[('前括号就压入栈中,接着判断后括号'}])'是否和栈顶括号是一对,若不是则返回False,匹配则弹出对应的前括号,直到整个字符串走完,若栈中还有前括号,则不匹配。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        for i in s:
            if i in '({[':
                stack.append(i)
            elif i == ')' and stack[-1] == '(':
                stack.pop()
            elif i == ']' and stack[-1] == '[':
                stack.pop()
            elif i == '}' and stack[-1] == '{':
                stack.pop()
            else:
                return False
        return len(stack) == 0

160. 相交链表

编写一个程序,找到两个单链表相交的起始节点。

例如,下面的两个链表

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

在节点 c1 开始相交。

注意:

  • 如果两个链表没有交点,返回 null.
  • 在返回结果后,两个链表仍须保持原有的结构。
  • 可假定整个链表结构中没有循环。
  • 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存
# -*- coding:utf-8 -*-
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
"""
先遍历第一个链表到他的尾部,然后将尾部的next指针指向第二个链表
(尾部指针的next本来指向的是null)。这样两个链表就合成了一个链表,
判断原来的两个链表是否相交也就转变成了判断新的链表是否有环的问题了:
即判断单链表是否有环? 
"""
class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        p1 = headA
        p2 = headB
        while p1 != p2:
            p1 = headB if p1 == None else p1.next
            p2 = headA if p2 == None else p2.next
        return p1

141. 环形链表

给定一个链表,判断链表中是否有环。

进阶:
你能否不使用额外空间解决此题?

思路:使用快慢两个指针,快指针比慢指针快一倍,若链表成环,快指针一定会赶上慢指针,而不是指向None。

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

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None or head.next == None:
            return False
        slow = head
        fast = head.next
        while slow != fast:
            if fast == None or fast.next == None:
                return False
            slow = slow.next
            fast = fast.next.next
        return True

14. 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

# -*- coding:utf-8 -*-
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        res = ''
        if strs == []:
            return res
        first = strs[0]
        for i in range(len(first)):
            for j in range(len(strs)):
                try:
                    if first[i] == strs[j][i]:
                        pass
                    else:
                        return res
                except:
                    return res
            else:
                res += first[i]
        return res

7. 反转整数

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

思路:将整数转化为字符串再逆序,考虑正数和负数两个情况,要注意的是整数的范围。

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        x = int(str(x)[::-1]) if x >= 0 else -int(str(-x)[::-1])
        return x if x < 2147483648 and x >= -2147483648 else 0

猜你喜欢

转载自blog.csdn.net/qq_41805514/article/details/82926219