20. Valid Parentheses-leetcode-java
先看題目要求
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.
此題見leetcode頻率分類表,是stack的題,但是開始沒用stack做,繞了個彎子。
思路:
最終採用 hashmap儲存值+stack方法解決。先將三個預設對存入map中,設定curr臨時變數儲存遍歷的每一個字元。如果current等於key,則進棧。如果current等於value,就判斷棧不為空,並且此時棧頂作為key對應的value值等於current,就將棧頂彈出。最後棧恰好為空,返回true。
public class Solution {
public boolean isValid(String s) {
//此題考查stack的運用,此法解決方案是hashmap搭配棧stack
Map<Character,Character> map= new HashMap<Character,Character>();
Stack<Character> st = new Stack<Character>();
map.put('(',')');
map.put('[',']');
map.put('{','}');
for(int i=0;i<s.length();i++){
char curr=s.charAt(i);
if(map.containsKey(curr)){
st.push(curr);
}else if(map.containsValue(curr)){
// if(st!=null && curr==st.peek()){
if(!st.empty() && map.get(st.peek())==curr){// get()這個方法是取key得到value不要搞混了,current此時是value哦
st.pop();
}else return false;
}
}
return st.empty();
}}
//以下是先前的錯誤思路,註釋掉了
/*
boolean valid=true;
int len=s.length();
if(len%2 !=0) return false;
char[] res=s.toCharArray();
int middle=len/2;
for(int i=0,j=middle-1;j<len-1;i++,j++){
if(res[i] != res[j]){
valid=false;
break;
}
}
for(int i=0;i<len-1;i++){
switch(res[i]){
case '(':
if(res[i+1] !=')')
{ valid=false;}
break;
case '[':
if(res[i+1] != ']')
{ valid=false;}
break;
case '{':
if(res[i+1] !='}')
{valid=false;}
break;
default:
break;
}
}
return valid;
}}
*/