马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 zltzlt 于 2019-8-31 17:59 编辑
今天的题目(有点小难哦):
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
1. 左括号必须用相同类型的右括号闭合。
2. 左括号必须以正确的顺序闭合。e$ *7!!Q
3. 注意空字符串可被认为是有效字符串。
这道题已结束,进入奖励阶段。
示例 2:
输入: "()[]{}"
输出: True 示例 4:
输入: "([)]"
输出: False 示例 5:
输入: "{[]}"
输出: True
我原来的解法:
- def is_valid(string):
- list1 = list(string)
- while list1:
- if list1.count("(") != list1.count(")"):
- return False
- elif list1.count('[') != list1.count("]"):
- return False
- elif list1.count("{") != list1.count("}"):
- return False
- for i, each in enumerate(list1):
- if list1[i] == "(":
- if list1[i + 1] == ")":
- list1.pop(i)
- list1.pop(i)
- else:
- try:
- index = list1.index(")")
- except ValueError:
- return False
- return is_valid("".join(list1[i + 1:index]))
- elif list1[i] == "[":
- if list1[i + 1] == "]":
- list1.pop(i)
- list1.pop(i)
- else:
- try:
- index = list1[i:].index("]")
- except ValueError:
- return False
- return is_valid("".join(list1[i + 1:index]))
- elif list1[i] == "{":
- if list1[i + 1] == "}":
- list1.pop(i)
- list1.pop(i)
- else:
- try:
- index = list1.index("}")
- except ValueError:
- return False
- return is_valid("".join(list1[i + 1:index]))
- return True
复制代码
改进后的解法:
- def fun(string: str):
- string = string.replace("()", "").replace("{}", "").replace("[]", "")
- if (string.count("(") != string.count(")") or string.count("[") !=
- string.count("]") or string.count("{") != string.count("}")):
- return False
- for i in range(2, len(string)):
- try:
- if (string[string.index("(") + i] == ")" or
- string[string.index("[") + i] == "]" or
- string[string.index("{") + i] == "}"):
- return False
- except ValueError:
- return False
- return fun(string) if string else True
复制代码
|