面对这个括号匹配的问题,我开始也有点迷茫,隐约觉得可以用栈(Stack)来解决。一起先来看看原题吧:
Given a string s 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.
Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
1
当成一个数学问题来看,先找出规则规律,如果先来一个关闭类型的括号(如),], }),那么直接就算false了,如果开和闭合没有成对出现,也会是false。我们可以拿一个Stack来保存open bracket,当循环的当前的字符是open bracket就push到stack。
当当前的字符是closed bracket则弹出顶部Stack的元素,看是否是对应的open bracket,如果是就继续循环,如果不是则返回false。
还要考虑一些边界情况,如果在弹出元素的时候刚好stack为空了,也说明没有配套的open bracket了,也应该返回false。
用Python实现的代码如下,非常清晰:
class Solution:
def isValid(self, s: str) -> bool:
bracketMap = {
"(": ")",
"{": "}",
"[": "]"
}
stack = []
for char in s:
if char in bracketMap:
# push the open bracket into the stack
stack.append(char)
else:
# If the stack is empty or do not have the matching open bracket, it means the closed bracket does not have the related open bracket
if len(stack) == 0 or bracke服务器托管tMap[stack.pop()] 服务器托管!= char:
return False
return len(stack) == 0
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
P2P网络介绍 P2P是Peer-to-Peer的缩写,“Peer”在英语里有“对等者、伙伴、对端”的意义。因此,从字面意思来看,P2P服务器托管网可以理解为对等网络。国内一些媒体将P2P翻译成“点对点”或者“端对端”,学术界则统一称为对等网络(Peer-to…