parsing - Match brackets the kotlin way -
i'm giving kotlin go; coding contently, have arraylist of chars want classify depending on how brackets matched:
(abcde) // ok characters other brackets can go anywhere )abcde( // ok matching brackets 'invertedly' ok (({()})) // ok )()()([] // ok ([)] // bad can't have different overlapping bracket pairs ((((( // bad brackets need have match my solution comes out(recursive):
//charlist property //recursion starter'upper private fun classifylistofcharacters() : boolean{ var j = 0 while (j < charlist.size ) { if (charlist[j].isbracket()){ j = checkmatchingbrackets(j+1, charlist[j]) } j++ } return j == commandlist.size } private fun checkmatchingbrackets(i: int, firstbracket :char) : int{ var j = while (j < charlist.size ) { if (charlist[j].isbracket()){ if (charlist[j].matchesbracket(firstbracket)){ return j //matched bracket normal/inverted } j = checkmatchingbrackets(j+1, charlist[j]) } j++ } return j } this works, how in kotlin? feels i've coded java in kotlin syntax
found functional languages better @ recursion, i've tried thinking in terms of manipulating functions , sending them down recursion no avail. i'd glad pointed in right direction, code, or pseudo-code of possible refactoring.
(omitted extension methods regarding brackets, think it's clear do)
another, possibly simpler approach problem maintaining stack of brackets while iterate on characters.
when encounter bracket:
if matches top of stack, pop top of stack;
if not match top of stack (or stack empty), push onto stack.
if brackets remain on stack @ end, means unmatched, , answer false. if stack ends empty, answer true.
this correct, because bracket @ position i in sequence can match 1 @ position j, if there's no unmatched bracket of different kind between them (at position k, i < k < j). stack algorithm simulates logic of matching.
basically, algorithm implemented in single for-loop:
val stack = stack<char>() (c in charlist) { if (!c.isbracket()) continue if (stack.isnotempty() && c.matchesbracket(stack.peek())) { stack.pop() } else { stack.push(c) } } return stack.isempty() i've reused extensions c.isbracket(...) , c.matchesbracket(...). stack<t> jdk class.
this algorithm hides recursion , brackets nesting inside abstraction of brackets stack. compare: current approach implicitly uses function call stack instead of brackets stack, purpose same: either finds match top character or makes deeper recursive call character on top.
Comments
Post a Comment