https://leetcode-cn.com/problems/valid-parentheses/description/
題目描述
給定一個只包括 '(',')'驼修,'{','}'诈铛,'['乙各,']' 的字符串,判斷字符串是否有效幢竹。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合耳峦。
左括號必須以正確的順序閉合。
注意空字符串可被認為是有效字符串焕毫。
示例
輸入: "()"
輸出: true
輸入: "()[]{}"
輸出: true
輸入: "([)]"
輸出: false
思路
1.將括號量化為數(shù)字蹲坷;
2.如果是左括號,則放進棧中邑飒,如果是右括號則與棧頂元素比較是否匹配循签,匹配則棧頂元素出棧;
3.考慮特殊情況:
- 輸入為空字符串
- 輸入的字符串只包含一個右括號
- 當棧為空疙咸,當前是右括號懦底,會溢出
代碼
class Solution {
public boolean isValid(String s) {
if (s.length()==0) {
return true;
}
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put('(', 1);
map.put(')', -1);
map.put('{', 2);
map.put('}', -2);
map.put('[', 3);
map.put(']', -3);
LinkedList<Integer> linkedList = new LinkedList<Integer>();
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i)) < 0 && linkedList.size()==0) {
return false;
}
if (map.get(s.charAt(i)) > 0) {
linkedList.add(map.get(s.charAt(i)));
} else {
if (linkedList.get(linkedList.size() - 1) + map.get(s.charAt(i)) == 0) {
linkedList.remove(linkedList.size() - 1);
} else {
return false;
}
}
}
return linkedList.size()==0;
}
}