背景本篇图文是LSGO软件技术团队组织的 第二期基础算法(Leetcode)刻意练习训练营 的打卡任务。本期训练营采用分类别练习的模式,即选择了五个知识点(数组、链表、字符串、树、贪心算法),每个知识点选择了 三个简单、两个中等、一个困难 等级的题目,共计三十道题,利用三十天的时间完成这组刻意练习。 本次任务的知识点:字符串 字符串或串(string) 是由数字、字母、下划线组成的一串字符。一般记为 s = “a1a2...an”(n >= 0) 。它是编程语言中表示文本的数据类型。 通常以串的整体作为操作对象,如:在串中查找某个子串在该串中首次出现的位置、在串的某个位置上插入一个子串以及删除一个子串等。两个字符串相等的充要条件是:长度相等,并且各个对应位置上的字符都相等。串通常以顺序的方式进行存储与实现。
题目给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true
示例 2: 输入: "()[]{}" 输出: true
示例 3: 输入: "(]" 输出: false
示例 4: 输入: "([)]" 输出: false
示例 5: 输入: "{[]}" 输出: true
示例 6: 输入: "" 输出: true
示例 7: 输入: "((" 输出: false
实现方式一:利用栈 思路:首先判断该字符串长度的奇偶性,如果是奇数,则返回false。否则,利用栈先进后出的特点,遇到“{”,“[”,“(”进行入栈操作,遇到“}”,“]”,“)”就与栈顶元素进行比较,如果是对应括号则出栈,否则返回false。 public class Solution { public bool IsValid(string s) { if (string.IsNullOrEmpty(s)) return true;
int count = s.Length; if(count%2 == 1) return false;
Stack<char> stack = new Stack<char>(); for (int i = 0; i < count; i++) { char c = s[i]; if (stack.Count == 0) { stack.Push(c); } else if(c == '[' || c == '{' || c == '(') { stack.Push(c); } else if (stack.Peek() == GetPair(c)) { stack.Pop(); } else { return false; } } return stack.Count == 0; }
public static char GetPair(char c) { if (c == ')') return '('; if (c == '}') return '{'; if (c == ']') return '['; return '\0'; } }
Python 语言 class Solution: def isValid(self, s: str) -> bool: dic = {")": "(", "}": "{", "]": "["} if s is None: return True
count = len(s) if count % 2 == 1: return False
lst = list() for i in range(count): c = s[i] if len(lst) == 0: lst.append(c) elif c == "[" or c == "{" or c == "(": lst.append(c) elif lst[-1] == dic[c]: lst.pop() else: return False return len(lst) == 0
|