-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatchDelimiters.java
More file actions
82 lines (68 loc) · 2.27 KB
/
Copy pathMatchDelimiters.java
File metadata and controls
82 lines (68 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.Stack;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Matching delimeters in a String.
*/
public class MatchDelimiters {
public static boolean isMatched(String expression){
final String opening = "({["; // opening delimiters
final String closing = ")}]"; // respective closing delimiters
Stack<Character> buffer = new Stack<>();
//For every character c within the expression
for(char c: expression.toCharArray()){
if(opening.indexOf(c) != -1){ // c is a left delimiter
buffer.push(c);
} else if(closing.indexOf(c) != -1) { // c is a right delimiter
if (buffer.isEmpty()) { return false; } // There are no Matches
if (closing.indexOf(c) != opening.indexOf(buffer.pop())){
return false; // Mismatched Delimiter
}
}
}
return buffer.isEmpty(); // Empty Stack -> All Opening Delimiters matched
}
/** Test Cases **/
@Test
public void simpleDelimeter(){
assertAll("",
() -> assertEquals(true,isMatched("()")),
() -> assertEquals(true,isMatched("{}")),
() -> assertEquals(true,isMatched("[]"))
);
}
@Test
public void validOne(){
assertTrue(isMatched("()(()){([()])}"));
}
@Test
public void validTwo(){
assertTrue(isMatched("( ) ( ( ) ) {( [ ( ) ] ) } "));
}
@Test
public void validThree(){
assertTrue(isMatched("(3) (3 + (4 - 5) ) {( [ ( ) ] ) } "));
}
@Test
public void validFour(){
assertTrue(isMatched("((()(()){([()])}))"));
}
@Test
public void validFive(){
assertTrue(isMatched("[(5+x)-(y+z)]"));
}
@Test
public void invalidOne(){
assertEquals(false,isMatched("("));
}
@Test
public void invalidTwo(){
assertEquals(false,isMatched("({[])}"));
}
@Test
public void invalidThree(){
assertEquals(false,isMatched(")(()){([()])}"));
}
}