Created
May 3, 2017 08:57
-
-
Save bastman/116f94bd744845e57d38ec95cd9c60b7 to your computer and use it in GitHub Desktop.
quick poc of matching balanced brackets, braces,...
This file contains hidden or 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
import java.util.List; | |
import java.util.Stack; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class StringMatcherApp { | |
public static void main(String[] args) { | |
String[] source = {"{}[]()", "{]}]"}; | |
System.out.println("source ..."); | |
Stream.of(source) | |
.forEach((v) -> { | |
System.out.println(v); | |
}); | |
String[] sink = StringMatcherApp.braces(source); | |
System.out.println("sink: ..."); | |
Stream.of(sink) | |
.forEach((v) -> { | |
System.out.println(v); | |
}); | |
} | |
public static String[] braces(String[] values) { | |
List<String> l = Stream.of(values) | |
.map(v -> { | |
if (check(v)) { | |
return "YES"; | |
} else { | |
return "NO"; | |
} | |
}).collect(Collectors.toList()); | |
return l.stream().toArray(String[]::new); | |
} | |
public static boolean check(String s) { | |
Stack<Character> stack = new Stack<Character>(); | |
for (int i = 0; i < s.length(); i++) { | |
char c = s.charAt(i); | |
if (c == '[' || c == '(' || c == '{') { | |
stack.push(c); | |
} else if (c == ']') { | |
if (stack.isEmpty()) return false; | |
if (stack.pop() != '[') return false; | |
} else if (c == ')') { | |
if (stack.isEmpty()) return false; | |
if (stack.pop() != '(') return false; | |
} else if (c == '}') { | |
if (stack.isEmpty()) return false; | |
if (stack.pop() != '{') return false; | |
} | |
} | |
return stack.isEmpty(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment