Simple Java Code without using stack


  • 0
    N

    public boolean isValid(String s) {
    String str = "";
    for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
    str += "" + s.charAt(i);
    } else {
    if (str.length() > 0) {
    char match = 0;
    switch (s.charAt(i)) {
    case ')':
    match = '(';
    break;
    case '}':
    match = '{';
    break;
    case ']':
    match = '[';
    break;
    }
    if (str.charAt(str.length() - 1) == match)
    str = str.substring(0, str.length() - 1);
    else
    return false;
    } else {
    return false;
    }
    }
    }
    return str.length() > 0 ? false : true;

    }

  • 0
    N
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.