sunfresh

Valid Parentheses

Jan 17th, 2023
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. Valid Parentheses
  2. Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
  3.  
  4. An input string is valid if:
  5.  
  6. Open brackets must be closed by the same type of brackets.
  7. Open brackets must be closed in the correct order.
  8. Every close bracket has a corresponding open bracket of the same type.
  9. class Solution {
  10. public boolean isValid(String s) {
  11.  
  12.  
  13. // Create a new stack to store the characters.
  14. Stack<Character> stack = new Stack<>();
  15.  
  16.  
  17. // convert string into char array and access the characters using for each loop.
  18. for(char ch: s.toCharArray())
  19. {
  20. // check ch
  21. switch (ch)
  22. {
  23. // open bracket then push it in stack.
  24. // close bracket then pop the item and compare.
  25. case '(':
  26. case '{':
  27. case '[':
  28. stack.push(ch);
  29. break;
  30. case ')':
  31. if(stack.isEmpty() || stack.pop() != '(')
  32.  
  33. // if the stack is empty then it means string have no open bracket.
  34. // hence it is invalid.
  35. {
  36. return false;
  37. }
  38. break;
  39. case '}':
  40. if(stack.isEmpty() || stack.pop() != '{')
  41. {
  42. return false;
  43. }
  44. break;
  45. case ']':
  46. if(stack.isEmpty() || stack.pop() != '[')
  47. {
  48. return false;
  49. }
  50. break;
  51. }
  52. }
  53.  
  54.  
  55. // After the loop we have to check one more condition.
  56. // return true only if the stack is empty.
  57. // if stack is not empty that means we have unused brackets.
  58.  
  59. if(stack.isEmpty())
  60. return true;
  61. else
  62. return false;
  63.  
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment