LeetCode---括号匹配

package DataDtructure;
import java.util.Stack;
/**
 * ClassName: Solution
 * Company:华中科技大学电气学院
 * date: 2019/8/23 15:18
 * author: YEXIN
 * version: 1.0
 * since: JDK 1.8
 * Description:解决括号匹配问题
 */
public class Solution {

    public boolean isValid(String s){
        Stack stack = new Stack<>();

        for(int i = 0;i < s.length(); i++){
            char c = s.charAt(i);
            if(c == '(' || c == '[' || c == '{'){
                stack.push(c);
            }
            else{
                if(stack.isEmpty())
                    return false;

                char topChar = stack.pop();
                if(c == ')' && topChar != '(')
                    return false;
                if(c == ']' && topChar != '[')
                    return false;
                if(c == '}' && topChar != '{')
                    return false;
            }

        }
        return stack.isEmpty();
    }
}

你可能感兴趣的:(LeetCode,Java)