Leetcode - 20

Leetcode No.20
级别:easy
给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:
输入: “()”
输出: true
示例 2:

输入: “()[]{}”
输出: true
示例 3:

输入: “(]”
输出: false
示例 4:

输入: “([)]”
输出: false
示例 5:

输入: “{[]}”
输出: true

解题思路一:栈
1. 当遇到 {, [, ( 时压入栈
2. 当遇到 }, ], ) 对比栈顶pop的数据是否是其对应的另一半
3. 当栈中为空时,说明匹配成功,否则匹配失败

解题思路二:栈
1. 当遇到 {, [, ( 时, 分别将 }, ], ) 压入栈
2. 当遇到 }, ], ) 对比栈顶pop的数据是否与其对应
3. 当栈中为空时,说明匹配成功,否则匹配失败

import java.util.Stack;

/**
 * @author stormxz
 * Leetcode - 23
 */
public class Leetcode {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //测试   false
        System.out.print(init_new_est("{(}[)]"));
    }

    public static boolean init_new(String str) {
        Stack<Character> stack = new Stack();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '{' || c == '[' || c == '(') {
                stack.push(c);
            } else {
                if (stack.isEmpty())
                    return false;
                char lastData = stack.pop();
                if (c == '}' && lastData != '{')
                    return false;
                if (c == ']' && lastData != '[')
                    return false;
                if (c == ')' && lastData != '(') 
                    return false;
            }
        }

        return stack.isEmpty();
    }

    public static boolean init_new_est(String str) {
        Stack<Character> stack = new Stack<Character>();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);

            if (c == '{')
                stack.push('}');

            else if (c == '[')
                stack.push(']');

            else if (c == '(')
                stack.push(')');

            else if (stack.isEmpty() || stack.pop() != c)
                return false;


        }
        return stack.isEmpty();
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_39158738/article/details/80909576