Skip to content

Instantly share code, notes, and snippets.

@JonathanLalou
Created June 29, 2021 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathanLalou/6285fb620ba1041921c5048aab11361c to your computer and use it in GitHub Desktop.
Save JonathanLalou/6285fb620ba1041921c5048aab11361c to your computer and use it in GitHub Desktop.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
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
final Deque<Character> cars = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
final Character car = s.charAt(i);
switch (car) {
case '(':
case '[':
case '{':
cars.push(car);
break;
case ')':
if (!cars.isEmpty() && '(' == cars.pop()) {
break;
} else {
return "NO";
}
case ']':
if (!cars.isEmpty() && '[' == cars.pop()) {
break;
} else {
return "NO";
}
case '}':
if (!cars.isEmpty() && '{' == cars.pop()) {
break;
} else {
return "NO";
}
}
}
return cars.isEmpty() ? "YES" : "NO";
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int t = Integer.parseInt(bufferedReader.readLine().trim());
IntStream.range(0, t).forEach(tItr -> {
try {
String s = bufferedReader.readLine();
String result = Result.isBalanced(s);
bufferedWriter.write(result);
bufferedWriter.newLine();
} catch (IOException ex) {
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