简体   繁体   中英

trying to check valid parentheses/bracket pairing

given a string of solely parentheses, brackets, etc., I'm trying to return true if the pairings are correct. (there are some similar questions but they involve more complicated stuff like arrays, other characters in the string, etc.)

here is my code, it returns false when I input "()"

class Solution {
    public boolean isValid(String s) {
        if (s.length() < 2) {
            return false;
        }

        for (int i = 0; i < s.length() - 1; i++) {
            char char1 = s.charAt(i);
            char char2 = s.charAt(i + 1);
            if ((int) char1 != (int) char2) {
                return false;
            }
        }
        return true;
    }
}

Any help or advice would be appreciated!

You could use a stack to solve this problem.

Assume that you start looping through the characters of your string and you have a stack ...

If you push onto the stack the opening brackets and then pop out of the stack the brackets when the corresponding closing brackets show up - you should have at the end of the inspection of the string an empty stack.

If the stack is empty at the end of the string loop, all parenthesis are paired.

If the stack is empty and there are still more characters to inspect (ie the loop did not finish) the parenthesis are not paired.

If you find a closing bracket and then pop from the stack and you find not the corresponding opening bracket, this means also that the parenthesis are not correctly paired. For this case you could use some code like:

private static boolean match(char fromStack, char next) {
    return fromStack == '[' && next == ']' || fromStack == '{' && next == '}' || fromStack == '(' && next == ')';
}

Right now you are just trying to make sure that 2 consecutive characters aren't the same, but ")(" and "(}" meet that condition and aren't valid pairs. Also as @luk2302 commented, you should iterate every 2 chars in the String. So instead of using i++ in your for loop, you should use i+=2 .

But I think that an alternative approach is using a regular expression for this:

public boolean isValid(String s) {
    // if null, or its length is zero or odd then is automatically invalid
    if (s == null || s.length() == 0 || s.length() % 2 != 0) {
        return false;
    }

    return s.matches("(\\(\\)|\\{\\}|\\[\\])+");
}

This regex will match the "()", "{}" and "[]" 1 or more times.

Here are some test outputs:

() is valid: true
)( is valid: false
(} is valid: false
()() is valid: true
()( is valid: false
(){}[] is valid: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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