LeetCode 문제 풀이 day 020 (Jieky)

18374 단어 LeetCode자바leetcode
LeetCode 20 번 문제
/*
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

Example 1:
Input: "()"
Output: true

Example 2:
Input: "()[]{}"
Output: true

Example 3:
Input: "(]"
Output: false

Example 4:
Input: "([)]"
Output: false

Example 5:
Input: "{[]}"
Output: true
*/
import java.util.*;
public class ValidParentheses{
     
	public static void main(String[] args){
     
	String str = "{[]}";
		ValidParentheses vp = new ValidParentheses();
		boolean result = vp.isValid02(str);
		System.out.println(result);
	}
	
	//   Character   String     
	public boolean isValid02(String s){
     
		if(s == null) return false;
		
		if(s != null && s.length() == 0) return true;
		
		HashMap<Character,Character> pairs = new HashMap<Character,Character>(); 
		pairs.put(')','(');
		pairs.put(']','[');
		pairs.put('}','{');
		
		Stack<Character> elements = new Stack<Character>();
		
		//           
		char[] array = s.toCharArray();
		
		for (int i=0;i<s.length();i++){
     
			char temp = array[i];
			//      
			if (temp == '(' || temp == '{' || temp == '['){
     
				elements.push(temp);
			//              ,         (              )
			}else if(!elements.empty() && pairs.get(temp) == elements.peek()){
     
				elements.pop();
			//              ,          
			}else{
     
				return false;
			}
		}
		
		//        ,          ,           
		if(elements.empty()){
     
			return true;
		}else{
     
			return false;
		}
	}
	
	public boolean isValid01(String s){
     
		if(s == null) return false;
		
		if(s != null && s.length() == 0) return true;
		
		HashMap<String,String> pairs = new HashMap<String,String>(); 
		pairs.put(")","(");
		pairs.put("}","{");
		pairs.put("]","[");
		
		Stack<String> elements = new Stack<String>();
		
		String temp = null;
		for (int i=0;i<s.length();i++){
     
			temp = s.substring(i,i+1);
			//      
			if (temp.equals("(") || temp.equals("{") || temp.equals("[")){
     
				elements.push(temp);
			//              ,         
			}else if(!elements.empty() && pairs.get(temp).equals(elements.peek())){
     
				elements.pop();
			//              ,          
			}else{
     
				return false;
			}
		}
		
		//        ,          ,           
		if(elements.empty()){
     
			return true;
		}else{
     
			return false;
		}
	}
}

좋은 웹페이지 즐겨찾기