Leetcode解题分析(3)(4)

url:https://leetcode.com/problems/longest-valid-parentheses/description/

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

【解题分析】本题是要求找出左右括号组成的字符串中最长合法的子字符串长度,这里可以用到栈这一数据结构。

【解题思路】将目标字符串中的字符逐个加入到栈中,若括号匹配成功,则将配对括号从栈中去除,向栈中压入数字1,若栈中该数字前还有数字,再将二者合并为一个数字,若构成一对括号中一个数字的结构,则去掉匹配的括号,将数字加1。说到这里你应该明白了,其实这里就是将合法的括号字符不断合并,用数字代表其匹配的括号数。接下来就很简单了,只要在栈中找到最大的数字即可。

【Tips】

①可以使用Python的列表表示栈这一数据结构

②注意所求的答案是匹配的括号字符数,其值等于括号匹配数乘以2

③在考虑括号匹配的时候,要考虑是否会出现越界的情况,边界条件很重要!!!

【答案(Accepted)】

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """


        stack = []
        for i in range(len(s)):
            if len(stack)==0:    #栈为空则压入
                stack.append(s[i])
                #print(stack)
                continue
            if s[i]=='(':    #压入
                stack.append(s[i])
            else:
                if stack[-1]=='(':    #匹配则换为1,并不断合并匹配数
                    stack[-1] = 1
                    while len(stack)>=2 and isinstance(stack[-2], int):
                        stack[-2] += stack[-1]
                        del stack[-1]
                elif len(stack)>=2 and isinstance(stack[-1], int) and stack[-2]=='(':   #构成“(数字)”的结构,并不断合并匹配数
                    stack[-1] += 1
                    del stack[-2]
                    while len(stack)>=2 and isinstance(stack[-2], int):
                        stack[-2] += stack[-1]
                        del stack[-1]
                else:
                    stack.append(s[i])
            #print(stack)
        max = 0
        for item in stack:  #找出最大匹配数
            if isinstance(item, int) and item > max:
                max = item
        return 2*max    #注意所求的为最大匹配括号字符数


题目:ZigZag Conversion

url:https://leetcode.com/problems/zigzag-conversion/description/


The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I
解答:
class Solution:
    def convert(self, s, numRows):
        if numRows <= 1:
            return s
        rows = ['' for i in range(0, numRows)]
        for i, c in enumerate(s):
            new_row = i % (2 * numRows - 2)
            if new_row > numRows - 1:
                new_row = 2 * numRows - new_row - 2
            rows[new_row] += c
        return ''.join(rows)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值