Created
November 14, 2023 12:24
-
-
Save prianichnikov/99835c5843f4b19ecd90e0aa5036527a to your computer and use it in GitHub Desktop.
Find correct brackets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.EmptyStackException; | |
import java.util.Map; | |
import java.util.Stack; | |
public class Solution { | |
public static void main(String[] args) { | |
System.out.println(isCorrectBrackets("[{}]")); | |
System.out.println(isCorrectBrackets("[{]}")); | |
System.out.println(isCorrectBrackets("[{}{}{}{}]")); | |
System.out.println(isCorrectBrackets("}}")); | |
} | |
static boolean isCorrectBrackets(String str) { | |
Stack<Character> stack = new Stack<>(); | |
Map<Character, Character> mappings = Map.of( | |
']', '[', | |
'}', '{'); | |
for (char bracket : str.toCharArray()) { | |
Character openBracket = mappings.get(bracket); | |
if (openBracket == null) { | |
stack.push(bracket); | |
} else { | |
char previousBracket; | |
try { | |
previousBracket = stack.pop(); | |
} catch (EmptyStackException e) { | |
return false; | |
} | |
if (previousBracket != openBracket) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment