Skip to content

Instantly share code, notes, and snippets.

@kishida
Last active February 1, 2023 15:09
Show Gist options
  • Save kishida/75620815d058510c6a6fef9c5965d123 to your computer and use it in GitHub Desktop.
Save kishida/75620815d058510c6a6fef9c5965d123 to your computer and use it in GitHub Desktop.
3種類のカッコがあるときの対応を検査する
package org.example;
import java.util.ArrayDeque;
import java.util.Map;
public class ThreeParenthesis {
public static void main(String[] args) {
System.out.println(check("test")); // true
System.out.println(check("()test")); // true
System.out.println(check("(tes(ss{tt}))")); // true
System.out.println(check("(tes[ss{tt}))")); // false
System.out.println(check("(tes[ss{tt}])")); // true
}
static final Map<Character, Character> pair = Map.of(
')', '(',
']', '[',
'}', '{');
static boolean check(String str) {
return check(str, new int[]{0}, (char)0);
}
static boolean check(String str, int[] pos, char parenthesis) {
for (; pos[0] < str.length();) {
char cur = str.charAt(pos[0]);
pos[0]++;
switch (cur) {
case '(', '[', '{' -> {
if (!check(str, pos, cur)) {
return false;
}
}
case ')', ']', '}' -> {
return pair.get(cur).equals(parenthesis);
}
}
}
return parenthesis == 0;
}
/*
static boolean check(String str) {
var stack = new ArrayDeque<Character>();
for (char ch : str.toCharArray()) {
switch (ch) {
case '(', '[', '{' -> stack.push(ch);
case ')', ']', '}' -> {
if (stack.isEmpty()) {
return false;
}
if (!stack.pop().equals(pair.get(ch))) {
return false;
}
}
}
}
return stack.isEmpty();
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment