Created
May 31, 2016 08:27
-
-
Save dolvik/25a773e5fd768d8f928641e9a407fd8c to your computer and use it in GitHub Desktop.
Properly nested string
This file contains 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
/* | |
A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: | |
S is empty; | |
S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; | |
S has the form "VW" where V and W are properly nested strings. | |
For example, the string "{[()()]}" is properly nested but "([)()]" is not. | |
*/ | |
var rb = { | |
"{": "}", | |
"[": "]", | |
"(": ")" | |
}; | |
function solution(s){ | |
var arr = []; | |
//Пробегаем по всей строке. | |
//Если текущий элемент - парный для предыдущего, то удаляем предыдущий из результирущего массива | |
//Иначе - доблавяем элемент в результирующий массив | |
//Т.о. массиив в итоге должен быть пустым, если строка сформирована правильно | |
//Есил строка пустая, то она также считается сформированной правильно - в массив ничего не добавляли | |
for (var i = 0, len = s.length; i < len; i ++){ | |
var c = s[i]; | |
if (i === 0){ | |
arr.push(c); | |
continue; | |
} | |
if (c === rb[arr[arr.length - 1]]){ | |
arr.pop(); | |
} | |
else{ | |
arr.push(c); | |
} | |
} | |
return arr.length ? 0 : 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment