0

java: incompatible types: char cannot be converted to java.lang.CharSequence

boolean checkParentheses(String str) {
    Deque<Character> stack = new ArrayDeque<>();  

    String k = "({[";
    String s = ")]}";
    for (int i = 0; i < str.length();i++ ) {
        if (k.contains(str.charAt(i))) {
            stack.push(str.charAt(i));
        } else if (s.contains(str.charAt(i))) {

            if (matching(stack.peek()) == str.charAt(i)) {
                return true;
            }
        } else {
            return false;
        }
    }
} 

what should I use instead of contains?

Netizen110
  • 1,644
  • 4
  • 18
  • 21

3 Answers3

2

indexOf with -1.

Something along these lines:

boolean checkParentheses(String str) {
    Deque<Character> stack = new ArrayDeque<>();

    String k = "({[";
    String s = ")]}";
    for (int i = 0; i < str.length();i++ ) {
        if (k.indexOf(str.charAt(i)) > -1) {
            stack.push(str.charAt(i));
        } else if (s.indexOf(str.charAt(i)) > -1) {

            if (matching(stack.peek()) == str.charAt(i)) {
                return true;
            }
        } else {
            return false;
        }
    }
    return false;
}

You could also use contains creating a new String. But that option is not that good (more ineficcient).

2nd option:

boolean checkParentheses(String str) {
    Deque<Character> stack = new ArrayDeque<>();

    String k = "({[";
    String s = ")]}";
    for (int i = 0; i < str.length(); i++) {
        if (k.contains(String.valueOf(str.charAt(i)))) {
            stack.push(str.charAt(i));
        } else if (s.contains(String.valueOf(str.charAt(i)))) {

            if (matching(stack.peek()) == str.charAt(i)) {
                return true;
            }
        } else{
            return false;
        }
    }
    return false;
}

The second option is rather ugly.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
0

Try using indexOf instead of contains. Contains requires a String (AKA CharSequence), but you have a char. Also you can refer : https://javamanikandan.blogspot.in/2018/01/java-string-indexof-method-example.html and https://javamanikandan.blogspot.in/2018/01/java-string-contains-method-explained.html

Mani
  • 259
  • 3
  • 6
0

Try this

k.contains(""+str.charAt(i))

the method contains works with String objects not Char