简体   繁体   English

有人可以解释我的方法有什么问题吗?

[英]Can someone explain what is wrong with my approach?

I was trying to attempt this problem.我试图尝试这个问题。 https://leetcode.com/problems/valid-parentheses/ . https://leetcode.com/problems/valid-parentheses/ However, I was confused if in the second for loop I can compare s.charAt(i) and stack.pop().但是,如果在第二个 for 循环中我可以比较 s.charAt(i) 和 stack.pop(),我感到很困惑。

Basically, my approach was such.基本上,我的方法是这样的。 Push the entire string to a stack, and then run through the first half of the stack using stack.charAt(i) and compare it to the second half using stack.pop().将整个字符串压入堆栈,然后使用 stack.charAt(i) 遍历堆栈的前半部分,并使用 stack.pop() 将其与后半部分进行比较。 I just wanted to know what might be going wrong in my code as I get a false value when expecting a true value.我只是想知道我的代码可能出了什么问题,因为我在期望一个真值时得到一个假值。 I am just trying to understand if my concept is flawed or not?我只是想了解我的概念是否有缺陷?

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        
        boolean done = false;
        
        if(s.length() < 2)
            return true;
        
        for(int i = 0; i < s.length(); i++){
            stack.push(s.charAt(i));
        }
        
        for(int i = 0; i < s.length()/2; i++){
            if(s.charAt(i) == stack.pop())
                done = true;
        }
        
        return done;   
    }
}

While your code might work for strings such as " {([])} " and " (()) ", you are assuming that the strings will be symmetrical.虽然您的代码可能适用于“ {([])} ”和“ (()) ”等字符串,但您假设这些字符串是对称的。 A valid input such as " {()[]} " will not pass in your code because it is not symmetrical.诸如“ {()[]} ”之类的有效输入不会传入您的代码,因为它不是对称的。 Modify your code to account for asymmetry.修改您的代码以解决不对称问题。 Hint: maybe pop 2 elements when the character is a closing character such as ")" "}" and "]".提示:当字符是结束字符如“)”“}”和“]”时,可能会弹出 2 个元素。

You are supposed to check if the parentheses in a string match: that for a '(' there is a matching ')' .您应该检查字符串中的括号是否匹配:对于'('有一个匹配')' However, note that the character '(' is not equal to the character ')' .但是,请注意字符'('不等于字符')'

Your code is checking if the string matches a pattern where the second half of the string is the first half of the string in reverse, like {[))[{ .您的代码正在检查字符串是否匹配字符串的后半部分是字符串前半部分的模式,例如{[))[{ In other words, you're checking if the input is a palindrome .换句话说,您正在检查输入是否为回文

The approach you should take is storing only the starting brackets in the stack:您应该采取的方法是仅将起始括号存储在堆栈中:

    for(int i = 0; i < s.length(); i++){
        if s.charAt(i) is an open bracket:
            stack.push(s.charAt(i));
        else:
            "pop" a character from stack
            if it's '(' make sure that s.charAt(i) is ')'
            if it's '[' make sure that s.charAt(i) is ']'
            if it's '{' make sure that s.charAt(i) is '}'
    }

Your code first iterates up to the middle of the string and populates the stack, and then from the middle to the end and pops the stack.您的代码首先迭代到字符串的中间并填充堆栈,然后从中间迭代到末尾并弹出堆栈。 In other words, you're implicitly assuming that the first half of a valid string is opening parentheses of various types, and the second is their corresponding closing parentheses (eg ([]) or {[()]} ).换句话说,您隐含地假设有效字符串的前半部分是各种类型的左括号,第二部分是它们对应的右括号(例如([]){[()]} )。 However, these aren't the only valid strings - there is no limitation that states that a closing parenthesis can't be followed by an opening one, as long as the pairs are matched - eg, (()()) is a valid string.然而,这些并不是唯一有效的字符串 - 没有任何限制表明右括号后不能跟左括号,只要配对匹配 - 例如, (()())是有效的细绳。

Instead of making assumptions on the position within the string, you should iterate over the string, and for each character, if it's an opening parenthesis push it to the stack, and if it's a closing parenthesis pop the stack and compare the two:不要对字符串中的 position 进行假设,您应该遍历字符串,对于每个字符,如果它是一个左括号,则将其推入堆栈,如果它是一个右括号,则弹出堆栈并比较两者:

private static final Map<Character, Character> PARENS = new HashMap<>();
static {
    PARENS.put('(', ')');
    PARENS.put('[', ']');
    PARENS.put('{', '}');
}
public static boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();

    for (int i = 0; i < s.length(); ++i) {
        char ch = s.charAt(i);
        if (PARENS.containsKey(ch)) {
            stack.push(ch);
        } else {
            if (stack.isEmpty()) {
                return false;
            }
            char match = stack.pop();
            if (ch != PARENS.get(match)) {
                return false;
            }
        }
    }

    return stack.isEmpty();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM