Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
Example 4:
Input: s = "([)]" Output: false
Example 5:
Input: s = "{[]}" Output: true
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
Solution
public static boolean isValidOrNot(String s) { boolean isValid = true; if (s.length() % 2 == 1) { isValid = false; } else { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if (c == '(') { stack.add(')'); } else if (c == '[') { stack.add(']'); } else if (c == '{') { stack.add('}'); } else { if (!stack.isEmpty() && c == stack.peek()) { stack.pop(); } else { isValid = false; break; } } } if (!stack.isEmpty()) { isValid = false; } } System.out.println(isValid); return isValid; }
public static void main(String[] args) { String s = "(("; boolean isValid = true; if (s.length() % 2 == 1) { isValid = false; } else { int[] chatArray = new int[s.length()]; int i = 0; for (char c : s.toCharArray()) { if (c == '(') { chatArray[i++] = ')'; } else if (c == '[') { chatArray[i++] = ']'; } else if (c == '{') { chatArray[i++] = '}'; } else { if (i != 0 && c == chatArray[i - 1]) { i--; } else { isValid = false; break; } } } if (i != 0) { isValid = false; } } System.out.println(isValid); }
Thanks for reading :)
Whether this post is helpful?
Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments. feedback are welcome...
No comments:
Post a Comment