20. 有效的括號
1、自己思路
首先想到的就是使用棧,
class Solution {
public boolean isValid(String s) {
ArrayList<Character> c = new ArrayList<Character>(); //定義棧
int c_top = -1; //定義棧的指針
for(int i=0; i<s.length(); i++){
if(c_top == -1){ //當前數組爲空
c.add(0,s.charAt(i));
c_top++;
continue;
}
switch(s.charAt(i)){
case ')':
if(c.get(c_top) == '('){
//出棧
c.remove(c_top);
c_top--;
}else{
//入棧
c_top++;
c.add(c_top, s.charAt(i));
}
break;
case ']':
if(c.get(c_top) == '['){
//出棧
c.remove(c_top);
c_top--;
}else{
//入棧
c_top++;
c.add(c_top, s.charAt(i));
}
break;
case '}':
if(c.get(c_top) == '{'){
//出棧
c.remove(c_top);
c_top--;
}else{
//入棧
c_top++;
c.add(c_top, s.charAt(i));
}
break;
default :
//入棧
c_top++;
c.add(c_top, s.charAt(i));
}
}
if(c_top == -1){
return true;
}else{
return false;
}
}
}
提交錯誤:
1、寫反了判斷符號,
2、沒有寫前符號入棧的操作
總結:
總的來說思路和官方的解答是一一致的。但是有幾個問題需要注意:
1、關於判斷的三種符號,我用的是switch進行判斷,最好的辦法應該是定義一個HashMap<Character,Character>
2、Java封裝了Stack這個類
2、官方的代碼,與一相同的思路
通過hashmap查找,找不到就是前符號,找到了就是後符號,直接到stack進行比較,判斷。這個做法非常巧妙,比我那種每個都去比較最後只是去比是否棧爲空要好。
決定重寫。。。。
class Solution {
public boolean isValid(String s) {
//構建hashmap
HashMap<Character, Character> hashmap = new HashMap<Character, Character>();
hashmap.put(')','(');
hashmap.put(']','[');
hashmap.put('}','{');
//構建棧,使用Java自帶的stack
Stack<Character> stack = new Stack<Character>();
for(int i=0; i<s.length(); i++){
//判斷是否存在,就證明了這個字符是前字符還是後字符
if(hashmap.containsKey(s.charAt(i))){
//獲取stack元素
//這裏要先判斷stack是否爲空,這裏使用的是教程的代碼,感覺處理的簡介
char topElement = stack.empty() ? '#' : stack.pop();
if(topElement!= hashmap.get(s.charAt(i))){
return false;
}
}else{
stack.push(s.charAt(i));
}
}
return stack.isEmpty();
}
}
提交錯誤:
1、topElement判斷不熟悉
2、創建HashMap不熟悉