/
Andrey_java_edu
/
Algorithms
Обзор
Документация
Войти
/
Andrey_java_edu
/
Algorithms
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/main/java/com/kamenskiy/io/ExStack.java
52 строки
1 KB
andrey
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
27 апр 2024, 01:22
27 апр 2024, 01:22
52684f3
Код
Авторство
О чём код?
package com.kamenskiy.io; import java.util.Stack; /* 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. Every close bracket has a corresponding open bracket of the same type. Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false */ public class ExStack { public static void main(String[] args) { boolean valid = isValid("[]"); System.out.println(valid); } public static boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(') { stack.push(')'); } else if (c == '[') { stack.push(']'); } else if (c == '{') { stack.push('}'); } else if (!stack.empty() && stack.peek() == s.charAt(i)) { stack.pop(); } else return false; } return stack.isEmpty(); } }