国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leet Code Stack Problem 棧問題合集

2019-11-10 22:21:31
字體:
來源:轉載
供稿:網友

總結

棧問題通常和對稱聯系起來,一個出現,必須和另一個出現才合法,例如,出現“(”,就要出現“)”才合法,當遇到對稱的問題時,可以考慮是不是棧問題

1. Leet Code Oj 20. Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

給定一個只包含字符’(’,’)’,’{‘,’}’,’[‘和’]’的字符串,確定輸入字符串是否有效。

括號必須以正確的順序關閉,“()”和“()[] {}”都有效,但“(]”和“([]]”不是。

代碼:

public class Solution { public boolean isValid(String s) { Stack<Integer> stack = new Stack<Integer>(); String rule = "()[]{}"; for(int i=0; i<s.length(); i++){ int index = rule.indexOf(s.substring(i, i+1)); if(index % 2 == 1){ if(stack.isEmpty() || stack.pop() != index-1){ return false; } }else{ stack.push(index); } } return stack.isEmpty(); }}

這里的思路是: “(”必須和“)”對應,因此定義一個rule = “(){}[]”,可見左邊的下標是偶數,右邊的下標是基數


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 凌源市| 锡林浩特市| 黄大仙区| 昌平区| 平度市| 建平县| 合作市| 内乡县| 澎湖县| 定南县| 长武县| 浙江省| 新巴尔虎左旗| 色达县| 株洲市| 东明县| 温州市| 偏关县| 霍城县| 凤翔县| 定日县| 延川县| 诸暨市| 眉山市| 牡丹江市| 东乡县| 天峨县| 手游| 许昌县| 天水市| 布尔津县| 昌乐县| 凤阳县| 休宁县| 临西县| 中山市| 甘肃省| 定结县| 志丹县| 贵州省| 古丈县|