1. 程式人生 > >Valid Parentheses 合法括號

Valid Parentheses 合法括號

 public boolean isValid(String s) {
        
        Stack<Character> stack = new Stack<Character>();
int i =0;
char []temp = s.toCharArray();
while(i<temp.length)
{
	   if(stack.isEmpty())
	   {
		   if(temp[i]=='('||temp[i]=='{'||temp[i]=='[')
		   {
			   stack.push(temp[i]);
			   i++;
		   }
		   else
			   return false;
		
	   }
	   else
	   {
		   if(temp[i]=='('||temp[i]=='{'||temp[i]=='[')
		   {
			   stack.push(temp[i]);
			   i++;
		   }
		   else
		   {
			   if(temp[i]==')'&&stack.peek()=='(')
			   {
				   stack.pop();
				   i++;
			   }
				  
			   else if(temp[i]=='}'&&stack.peek()=='{')
			   {
				   stack.pop();
				   i++;
			   }
			   else if(temp[i]==']'&&stack.peek()=='[')
			   {
				   stack.pop();
				   i++;
			   }
			   else 
				   return false;
			  
		   }
		   
	   }
	  
	   
	   
}
return stack.isEmpty();
        
    }