Skip to content

Commit

Permalink
Solve validParentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
gusaiani committed Nov 20, 2019
1 parent 421f27b commit 346f949
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
2 changes: 1 addition & 1 deletion tests/validParentheses.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,6 @@ test('{}{}()[] should return true', () => {
expect(validParentheses('{}{}()[]')).toBeTruthy()
})

test.only('{}[{}]((){})(){} should return true', () => {
test('{}[{}]((){})(){} should return true', () => {
expect(validParentheses('{}[{}]((){})(){}')).toBeTruthy()
})
24 changes: 11 additions & 13 deletions validParentheses.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ function validParentheses(str) {
}

function isArrayValid(arr) {
debugger
if (!arr.length) return true
if (arr.length % 2 !== 0) return false

Expand All @@ -27,24 +26,23 @@ function isArrayValid(arr) {
return false
}

if (arr[1] === closers[initialChar]) {
hasFoundCloser = true
const clippedArray = arr.slice(2)
if (!isArrayValid(clippedArray)) return false
} else {
// Instead of looping backwards, we have to
// 1. Loop forward
// 2. Count other openings of the same opener
// 3. Count closings too
// 4. Once we get to the same number of closers as we had openers, that's the index to slice the array.
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] === closers[initialChar]) {
let initialsFound = 1

for (let i = 1; i <= arr.length; i++) {
if (arr[i] === initialChar) {
initialsFound++
}

if (arr[i] === closers[initialChar]) {
if (initialsFound === 1) {
hasFoundCloser = true
const arr1 = arr.slice(1,i)
const arr2 = arr.slice(i+1)
if (!isArrayValid(arr1)) return false
if (!isArrayValid(arr2)) return false
break;
} else {
initialsFound--
}
}
}
Expand Down

0 comments on commit 346f949

Please sign in to comment.