-
Notifications
You must be signed in to change notification settings - Fork 0
/
practice-teste-turing.js
92 lines (80 loc) · 1.99 KB
/
practice-teste-turing.js
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
83
84
85
86
87
88
89
90
91
/**
* Valid Parentheses - "Practice test" of Turing.com platform code tests...
*
* 1) open brackets must be closed by the same type of brackets
* 2) open brackets must be closed in the correct order
*
* examples:
* s = "{[())}" => invalid
* s = "{[](){()}[({})]}()" => valid
* s = "{[]{}([])}" => valid...
*
* strategic: for each open bracket, I count how many chars there are until the respective close bracket
* this quantity must be EVEN
* How to be sure about what is the exact closing bracket? jumping new open and close brackets "inside"...
*
*
*/
function findCloseBracket(sx,i,endBracket){
var result = true;
var found = false;
var jump = 0;
var j = i+1;
var countInside = 0;
while (j < sx.length && found==false) {
if(sx[j] == sx[i]) {
jump++;
}
if(sx[j] == endBracket) {
if(jump == 0) {
found = true;
} else {
jump--;
j++;
countInside++;
}
}else{
j++;
countInside++;
}
}
if(found==false){
result = false;
}else{
if(countInside > 1 && countInside %2 != 0){
result = false;
}
}
return result;
}
const isValid = function(s){
// leap size...
var result = (s.length%2==0);
let i = 0;
while (i < s.length && result == true) {
switch(s[i]){
case "{":
result = findCloseBracket(s,i,"}");
break;
case "(":
result = findCloseBracket(s,i,")");
break;
case "[":
result = findCloseBracket(s,i,"]");
break;
}
i++;
}
return result;
}
// {}()[]
//var s = "{}";
var s = "{[((])}]" // invalid
//var s = "{[](){()}[({})]}([])" // valid
//var s = "{[]{}([])}" // valid...
// var s = '('
if (isValid(s)) {
console.log('is valid... :-))))');
}else{
console.log('invalid... :-((((');
}