Skip to content

Commit

Permalink
Create ValidParentheses.java
Browse files Browse the repository at this point in the history
  • Loading branch information
harshithasudhakar authored Mar 11, 2024
1 parent 70ecfda commit 6372701
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Stacks/Problems/ValidParentheses.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import java.util.Scanner;

class ValidParentheses {
public static boolean isValid(String s) {
StringBuilder check = new StringBuilder();

for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '[' || ch == '{') {
check.append(ch);
} else {
if (check.length() == 0) {
return false;
}

char lastOpenChar = check.charAt(check.length() - 1);
if ((ch == ')' && lastOpenChar == '(') || (ch == ']' && lastOpenChar == '[') || (ch == '}' && lastOpenChar == '{')) {
check.deleteCharAt(check.length() - 1);
} else {
return false;
}
}
}

return check.length() == 0;
}

public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String s = input.nextLine();
System.out.println(isValid(s));
}
}

0 comments on commit 6372701

Please sign in to comment.