提升面试竞争力:精通“有效括号”问题,斩获心仪offer

职场   2024-12-09 13:00   北京  

今天我们总结几个面试官容易问的面试题
有效括号
这是LeetCode上的一道算法题,旨在考察考生对“栈”数据结构的熟悉程度。我们来看一下。
给定一个仅包含字符‘(‘、‘)’、‘{‘、‘}’、‘[‘和‘]’的字符串 s,确定输入字符串是否有效。
如果满足以下条件,输入字符串有效:开括号必须由相同类型的括号括起来。左括号必须按正确的顺序关闭。
示例1:
Input: s = "()"Output: true
示例2:
Input: s = "()[]{}"Output: true
示例3:
Input: s = "(]"Output: false
示例4:
Input: s = "([)]"Output: false
示例5:
Input: s = "{[]}"Output: true
限制条件:
  • 1 <= s.length <= 104
  • s 仅由括号‘()[]{}’组成
问题信息
如果我们真的没学过算法,也不知道那么多套路,那么通过问题和例子来获取尽可能多的信息是非常重要的。
那么,我们可以得到以下信息:
  • 字符串 s 的长度必须是偶数,不能是奇数(成对匹配)。
  • 右括号前面必须有左括号。
方法一:暴力消除
得到以上信息后,我想既然[]、{}、()是成对出现的,那我是不是可以一一消除呢?如果最后的结果是空字符串,那不是就说明符合题意了吗?
例如:
Input: s = "{[()]}"
Step 1: The pair of () can be eliminated, and the result s is left with {[]}Step 2: The pair of [] can be eliminated, and the result s is left with {}Step 3: The pair of {} can be eliminated, and the result s is left with '', so it returns true in line with the meaning of the question
代码:
const isValid = (s) => {while (true) {let len = s.length// Replace the string with '' one by one according to the matching pair s = s.replace('{}', '').replace('[]', '').replace('()', '')// There are two cases where s.length will be equal to len// 1. s is matched and becomes an empty string// 2. s cannot continue to match, so its length is the same as the len at the beginning, for example ({], len is 3 at the beginning, and it is still 3 after matching, indicating that there is no need to continue matching, and the result is falseif (s.length === len) {return len === 0 } }}
暴力消除方式还是可以通过LeetCode的用例,但是性能差了一点,哈哈。
方法二:使用“栈”来解决
主题信息中的第二项强调对称性。栈(后进先出)和(推入和弹出)正好相反,形成明显的对称性。
例如
Input: abcOutput: cba
“abc”和“cba”是对称的,所以我们可以尝试从堆栈的角度来解析:
Input: s = "{[()]}"
Step 1: read ch = {, which belongs to the left bracket, and put it into the stack. At this time, there is { in the stack.
Step 2: Read ch = [, which belongs to the left parenthesis, and push it into the stack. At this time, there are {[ in the stack.
Step 3: read ch = (, which belongs to the left parenthesis, and push it into the stack. At this time, there are {[( in the stack.
Step 4: Read ch = ), which belongs to the right parenthesis, try to read the top element of the stack (and ) just match, and pop ( out of the stack, at this time there are {[.
Step 5: Read ch = ], which belongs to the right parenthesis, try to read the top element of the stack [and ] just match, pop the [ out of the stack, at this time there are {.
Step 6: Read ch = }, which belongs to the right parenthesis, try to read the top element of the stack { and } exactly match, pop { out of the stack, at this time there is still '' in the stack.
Step 7: There is only '' left in the stack, s = "{[()]}" conforms to the valid bracket definition and returns true.
代码
const isValid = (s) => {// The empty string character is validif (!s) {return true }const leftToRight = {'(': ')','[': ']','{': '}' }const stack = []for (let i = 0, len = s.length; i < len; i++) {const ch = s[i]// Left parenthesisif (leftToRight[ch]) {stack.push(ch) } else {// start matching closing parenthesis// 1. If there is no left parenthesis in the stack, directly false// 2. There is data but the top element of the stack is not the current closing parenthesisif (!stack.length || leftToRight[ stack.pop() ] !== ch) {return false } } }// Finally check if the stack is emptyreturn !stack.length}
虽然暴力方案符合我们的常规思维,但是堆栈结构方案会更加高效。
最后
在面试中,算法是否应该成为评价候选人的重要指标,我们不会抱怨,但近年来,几乎每家公司都将算法纳入了前端面试中。为了拿到自己喜欢的offer,复习数据结构、刷题还是有必要的。

推荐一个受到超多好评的终生学习小程序「千锋学习站」

全网超火的课程资源:涵盖18个IT行业热门课程,3000G精品授课视频,从入门到精通,理论+实战,小白适用!
全网超牛的公开课:定期邀请一线大厂大佬来直播间宣讲,全程干货,福利满满,从基础理论到实战案例,分享实战IT技能,拒绝纸上谈兵!
全网超全的题库资源:1800个知识点练习,10万道面试真题,沉浸式刷题练习,帮助各位同学夯实基础,提升技术水平,为升职加薪保驾护航!
— 不负每份期待,继续与你共同成长—
点击下方小卡片,开始学习吧
👇👇👇

End -

想要获得技能提升和职业发展
点击即可学习免费好课哦!
 
 
免费好课推荐:
 Linux云计算 | Java开发 | 鸿蒙 | Python数据分析 | 物联网 | 网络安全 | 游戏原画 | 软件测试 | Unity游戏 | PMP项目管理 | HTML5大前端 | 全媒体运营 | UI/UE设计 | 影视剪辑 | C++ | 大数据 | 计算机二级



大前端私房菜
每天推出前端开发技巧、工具资源、项目实战等主题内容。在这里,你可以找到前端性能优化的私房秘籍,JavaScript 个性化框架的私房推荐,也有过时技术的私房警示。期待在公众号与更多小伙伴相遇!我们一起进步,共同成长
 最新文章