Last active
June 24, 2020 13:13
-
-
Save GeorgePaiva/8ba3dc774052292f07de55373df76a6a to your computer and use it in GitHub Desktop.
This file contains 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
package desafiometa; | |
import java.util.Scanner; | |
import java.util.Stack; | |
public class Questao02 { | |
public static void main(String[] args) { | |
try (Scanner scr = new Scanner(System.in)) { | |
System.out.print("Digite os Brackets: "); | |
String expressao = scr.next(); | |
boolean resposta = Balanceado(expressao); | |
if (resposta) | |
System.out.println("SIM"); | |
else | |
System.out.println("NÃO"); | |
} | |
} | |
public static boolean Balanceado(String expressao) { | |
Stack<Character> openBrackets = new Stack<Character>(); | |
for (Character c : expressao.toCharArray()) { | |
if (Aberto(c)) { | |
openBrackets.push(c); | |
} else if (openBrackets.isEmpty()) { | |
return false; | |
} else { | |
Character open = openBrackets.pop(); | |
if (!Par(open, c)) { | |
return false; | |
} | |
} | |
} | |
if (openBrackets.size() > 0) { | |
return false; | |
} | |
return true; | |
} | |
private static boolean Aberto(Character c) { | |
return c != null && (c.equals('(') || c.equals('[') || c.equals('{')); | |
} | |
private static boolean Par(Character aberto, Character fechado) { | |
if (aberto == null || fechado == null) { | |
return false; | |
} else if (aberto.equals('(') && fechado.equals(')')) { | |
return true; | |
} else if (aberto.equals('[') && fechado.equals(']')) { | |
return true; | |
} else if (aberto.equals('{') && fechado.equals('}')) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment