Created
October 13, 2021 18:39
-
-
Save enzobonggio/0e338de8de8641828231708588ec006c 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
public class BraceChecker { | |
public static void main(String[] args) { | |
testPalabra("()", true); | |
testPalabra("(()", false); | |
testPalabra("([{()}])", true); | |
testPalabra("([[{{}}])", false); | |
testPalabra(")", false); | |
testPalabra("(", false); | |
} | |
public static boolean isValid(String palabra) { | |
boolean valida = true; | |
int[] contadorCaracteres = {0, 0, 0}; //index 0=() 1=[] 2={} | |
String secuenciaAperturas = ""; | |
for (int i = 0; i < palabra.length(); i++) { | |
char caracter = palabra.charAt(i); | |
if (esCaracterEspecial(caracter)) { | |
cuentaCaracter(caracter, contadorCaracteres); | |
if (caracterCierra(caracter)) { | |
if (esPar(caracter, contadorCaracteres) && caracter == secuenciaAperturas.charAt(secuenciaAperturas.length() - 1)) { | |
secuenciaAperturas = secuenciaAperturas.substring(0, secuenciaAperturas.length() - 2); | |
} else { | |
valida = false; | |
break; | |
} | |
} else { //caracter abre | |
secuenciaAperturas += caracter; | |
} | |
} else { | |
valida = false; | |
break; | |
} | |
} | |
return valida; | |
} | |
private static void testPalabra(String palabra, boolean shouldBe) { | |
System.out.println("Validación de '" + palabra + "': es " + isValid(palabra) + " deberia ser: " + shouldBe); | |
} | |
private static boolean esPar(char caracter, int[] contadorCaracteres) { | |
short index; | |
switch (caracter) { | |
case 41: { | |
index = 0; | |
} | |
break; | |
case 93: { | |
index = 1; | |
} | |
break; | |
case 125: { | |
index = 2; | |
} | |
break; | |
default: { | |
return false; | |
} | |
} | |
return contadorCaracteres[index] % 2 == 0; | |
} | |
private static void cuentaCaracter(char caracter, int[] contadorCaracteres) { | |
switch (caracter) { | |
case 40: { | |
contadorCaracteres[0]++; | |
} | |
break; | |
case 41: { | |
contadorCaracteres[0]--; | |
} | |
break; | |
case 91: { | |
contadorCaracteres[1]++; | |
} | |
break; | |
case 93: { | |
contadorCaracteres[1]--; | |
} | |
break; | |
case 123: { | |
contadorCaracteres[2]++; | |
} | |
break; | |
case 125: { | |
contadorCaracteres[2]--; | |
} | |
break; | |
} | |
} | |
private static boolean esCaracterEspecial(char caracter) { | |
return caracter == 40 || caracter == 41 || caracter == 91 || caracter == 93 || caracter == 123 || caracter == 125; | |
} | |
private static boolean caracterCierra(char caracter) { | |
return caracter == 41 || caracter == 93 || caracter == 125; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment