Description:
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
Example:
The brackets must close in the correct order,"()"
and"()[]{}"
are all valid but"(]"
and"([)]"
are not.
思路分析:
1.這個問題不僅僅是要求 ‘(’字符 與 ‘)’字符 需要成對出現,而且要求“開閉”緊湊,所以來回遍歷逐個查找匹配肯定不行;
2.分析問題的特征,最主要的就是合法的輸入是很規范的“有開有閉”類型,即能夠通過在字符間插入特定數目的豎線,使得整個字符串各個局部都對稱,對‘棧’敏感一點的其實能夠慢慢聯想到這一數據結構,一進一出、兩進兩出...其實都展示着一種對稱;
3.因此,合法的輸入一定可以通過‘棧’這一數據結構的pop,push操作完成一個個完整的進出過程。
代碼思路:
step1:初始化棧,並入棧輸入串的第一個字符;
step2: 從輸入串的第二個字符到最后一個字符,依次與棧頂元素對比,棧不為空且棧頂元素與字符匹配則出棧,否則入棧該字符;
Step3: 操作完最后一個字符后,如果棧為空(即有進必有出,各個局部均對稱),則輸入合法;
C#代碼:
1 public class Solution { 2 public bool IsValid(string s) { 3 //step1 4 Stack<char> stk = new Stack<char>(); 5 char[] sArr = s.ToCharArray(); 6 stk.Push(sArr[0]); 7 for(int i = 1;i<s.Length;i++){ 8 //step2 9 if(stk.Count!=0&&IsMatch(stk.Peek(),sArr[i])){ 10 stk.Pop(); 11 }else{ 12 stk.Push(sArr[i]); 13 } 14 } 15 //step3 16 return stk.Count==0; 17 } 18 public bool IsMatch(char a,char b){ 19 if((a=='('&&b==')')||(a=='['&&b==']')||(a=='{'&&b=='}')) return true; 20 return false; 21 } 22 }