-1

i have an assessment here,and i provided a solution but when i run the code,the result is weird. Here is the assessment: "You are given a sequence of characters consisting of parentheses ( ) and brackets [ ].

A String of this type is said to be correct:

  • if it is an empty or null string
  • if the string A is correct ,(A) and [A] are correct
  • if the string A and B are correct the concatenation AB is also correct

input: The string contains at most 10000 characters.

Examples:[( )] is correct ,(( )[ ]) is correct,( [ ) ] is not correct,(( is not correct.

Implement the method check(String str) to check the correctness of a string of this type. check returns true if the string is correct,false otherwise. "

So i did that code below:

public class Solution {
    
    public static boolean check(String str) {
         String str1 = null,str2 = null;
         if(str==null|| str.length()==0) return true;
         if (check(str1)==true && check(str2)==true) {
             return true;
         }
        return false;
    }
    public static void main(String[] args) {
        
        System.out.println(Solution.check("([])"));    //true
        System.out.println(Solution.check("()[]"));    //true
        System.out.println(Solution.check("([)]"));    //false
        System.out.println(Solution.check("(("));      //false
        System.out.println(Solution.check("[(()])"));   //false

    }

}

But i run it and i get:

true
true
true
true
true

How can i fix it?

bassouat
  • 69
  • 2
  • 11
  • 3
    Whatevery you intendet to do with the line `char stack = [],c;` it certainly isn't valid java. – OH GOD SPIDERS Jan 21 '21 at 17:01
  • Related: https://stackoverflow.com/questions/4537980/equivalent-to-push-or-pop-for-arrays – jarmod Jan 21 '21 at 17:03
  • By stepping back. By understanding that there is a difference between compiling and running java code. And that you ensure your code compiles before you run it. You're see that line that defines that char stack makes absolutely no sense whatsoever. The syntax is so wrong, I really can't even guess what you tried to express there. – GhostCat Jan 21 '21 at 17:04
  • ok should i write like this: char stack =='[ ]'? – bassouat Jan 21 '21 at 17:04
  • ok , i deleted the stack,but i need it to follow my logic – bassouat Jan 21 '21 at 17:11
  • Relax,calm down @GhostCat,i have just fixed my code and it runs but it doesn't display the requirements(true,true,false,false,false) – bassouat Jan 21 '21 at 17:20
  • @bassouat you haven't fixed it if it's not doing what you want. Think about this line: `if (check(str1)==true && check(str2)==true) {`. What are the values of `str1` and `str2` there? And, consequently, what are the values of `check(str1)` and `check(str2)`? – Andy Turner Jan 21 '21 at 17:29
  • @Andy Turner str1 and str2 are 2 strings which are correct and following the statement if a `string str1` is correct then `check(str1)==true`; – bassouat Jan 21 '21 at 17:40
  • I didn't ask their type: I asked what their *values* are. Hint: it's always the same, and you should think whether that is appropriate. – Andy Turner Jan 21 '21 at 17:42
  • You don't set str1 or str2 to any value other than null. And check(null) is true. – NomadMaker Jan 21 '21 at 18:47

3 Answers3

1
import java.util.Stack;

public class HelloWorld {
    public static void main(String []args) {
        System.out.println(check("([])"));    //true
        System.out.println(check("()[]"));    //true
        System.out.println(check("([)]"));    //false
        System.out.println(check("(("));      //false
        System.out.println(check("[(()])"));   //false
         System.out.println(check("([(([]))][]())"));   //true
    }
    
    public static boolean check(String v) {
        if (v == null || v.isEmpty()) return true;
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < v.length(); ++i) {
            char c = v.charAt(i);
            if (c == '(' || c == '[') {
                stack.push(c);
            } else if (stack.isEmpty()) {
                return false;
            } else if ((stack.peek() == '(' && c == ')') || (stack.peek() == '[' && c == ']')) {
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }
}

Use stack is right.

vipcxj
  • 840
  • 5
  • 10
  • 1
    Don't dump code: to be a good answer, you need to actually explain why OP's approach didn't work, what you've changed, why you changed it etc. – Andy Turner Jan 21 '21 at 17:42
  • thanks for that answer,it works,so i was right from the beginning,i have to use `stack` – bassouat Jan 21 '21 at 17:52
  • @bassouat Yes, this is one way to do it. However, you couldn't use a stack they way you tried it in your "code". – NomadMaker Jan 22 '21 at 03:54
  • @bassouat No. Because `stack` means nothing in Java. `java.util.Stack` is a meaningful thing, but just "stack" is not. You are still struggling with very basic things. – GhostCat Jan 22 '21 at 07:23
1

I'm not going to answer how to do it correctly; I'll answer why what you have is wrong:

public static boolean check(String str) {
     String str1 = null,str2 = null;
     if(str==null|| str.length()==0) return true;
     if (check(str1)==true && check(str2)==true) {
         return true;
     }
    return false;
}

Let's look in more detail:

     if(str==null|| str.length()==0) return true;

So, if you pass in null, it returns true.

     if (check(str1)==true && check(str2)==true) {
         return true;
     }
    return false;

At this point, you've assigned the value null to both str1 and str2. So you're calling

     if (check(null)==true && check(null)==true) {

and, since check(null) is true, the condition evaluates to true, hence you return true from the method.

As such, your method cannot ever return false.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

A stack-based solution is based on checking the balance of opening and closing brackets:

  • the string would be valid when each closing bracket or parenthesis has its opening counterpart on the top of the stack, otherwise the string is invalid:
public static boolean check(String str) {
    if (null == str || str.isEmpty()) {
        return true;
    }
    // System.out.print(str + " -> ");
    Deque<Character> stack = new ArrayDeque();
    
    for (char c : str.toCharArray()) {
        if (c == ']' || c == ')') {
            if (stack.isEmpty()) {
                return false;
            }
            char prev = stack.pop();
            if (prev != '[' && c == ']' || prev != '(' && c == ')') {
                return false;
            }
        } else if (c == '[' || c == '(') {
            stack.push(c);
        } else {
            return false;
        }
    }
    return stack.isEmpty();
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42