題目
給定一個只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判斷字符串是否有效。有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。
示例 1:
輸入: "()"
輸出: true
示例 2:
輸入: "()[]{}"
輸出: true
示例 3:
輸入: "(]"
輸出: false
示例 4:
輸入: "([)]"
輸出: false
示例 5:
輸入: "{[]}"
輸出: true
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/valid-parentheses
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題思路
1.字符數長度爲偶數
2.左括號的數目爲字符長度的一半
3.構建長度爲字符串長度一半的數組作爲棧
3.從index=0開始,遇見左括號就入棧,index+1,
4.遇到右括號就從index-1取值存入的左括號比對,比對成功就進入下個循環,比對失敗就退出
5.若index小於0,或者index大於字符長度的一半說明左右括號數目不對等
解題代碼
public boolean isValid1(String s) {
int len = s.length();
if(len == 0){
return true;
}
if((len&1) == 1){
return false;
}
int[] stack = new int[len>>1];
int left = 0;
for(int i = 0 ; i<len ;i++){
int value = switchSymbol(s.charAt(i));
if(value>0){
if(left == stack.length){
return false;
}
stack[left++] = value;
continue;
}
left--;
if(left < 0 || stack[left]+value !=0){
return false;
}
}
return left == 0;
}
private int switchSymbol(char symbol) {
switch (symbol){
case '{':
return 1;
case '}':
return -1;
case '(':
return 2;
case ')':
return -2;
case '[':
return 3;
case ']':
return -3;
default:
return 0;
}
}