Created
July 2, 2022 15:15
-
-
Save yoosinpaddy/a886620b8995736959f5d04c9e2a7c21 to your computer and use it in GitHub Desktop.
Bracket validator java. Check if code brackets match java
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 com.company; | |
import java.io.*; | |
import java.util.*; | |
import java.util.stream.*; | |
class Result { | |
/* | |
* Complete the 'isBalanced' function below. | |
* | |
* The function is expected to return a STRING. | |
* The function accepts STRING s as parameter. | |
*/ | |
public static String isBalanced(String s) { | |
// Write your code here | |
Stack<String> h = new Stack(); | |
for (String f : s.split("")) { | |
switch (f) { | |
case ")": | |
if(!h.empty()&&h.peek().contentEquals("(")){ | |
h.pop(); | |
}else{ | |
return "NO"; | |
} | |
break; | |
case "}": | |
if(!h.empty()&&h.peek().contentEquals("{")){ | |
h.pop(); | |
}else{ | |
return "NO"; | |
} | |
break; | |
case "]": | |
if(!h.empty()&&h.peek().contentEquals("[")){ | |
h.pop(); | |
}else{ | |
return "NO"; | |
} | |
break; | |
default: | |
h.push(f); | |
} | |
} | |
return h.empty()?"YES":"NO"; | |
} | |
} | |
public class Solution { | |
public static void main(String[] args) throws IOException { | |
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); | |
BufferedWriter bufferedWriter = null; | |
try { | |
File f = new File("s.txt"); | |
if (!f.exists()) { | |
System.out.println(f.createNewFile()); | |
} | |
bufferedWriter = new BufferedWriter(new FileWriter(f.getName())); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
int t = Integer.parseInt(bufferedReader.readLine().trim()); | |
BufferedWriter finalBufferedWriter = bufferedWriter; | |
IntStream.range(0, t).forEach(tItr -> { | |
try { | |
String s = bufferedReader.readLine(); | |
String result = Result.isBalanced(s); | |
finalBufferedWriter.write(result); | |
finalBufferedWriter.newLine(); | |
} catch (IOException ex) { | |
System.out.println(ex.getMessage()); | |
throw new RuntimeException(ex); | |
} | |
}); | |
bufferedReader.close(); | |
bufferedWriter.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment