I know I'm a little late for this party; this is also my very first post on StackOverflow.
But when I looked through the answers, I thought that I could come up with a better solution.
So my solution is to use multiple pointers.
It should not even use RAM memory, since registers can be used for this.
I have not tested the code; he wrote it on the fly.
You will need to correct my typos and debug it, but I believe that you will get this idea.
Memory usage: in most cases, only the central processor is registered.
CPU usage: it depends, but about twice as much time spent reading a line. Changes memory: None.
b: string b eginning, e: string e nd.
l: l position eft, r: r position.
c: c har, m: m atch char
if r reaches the end of the line, we are successful.
l goes back from r to b.
Whenever r meets a new start type, set l = r.
when l reaches b, we are done with the block; go to the beginning of the next block.
const char *chk(const char *b, int len) { char c, m; const char *l, *r; e = &b[len]; l = b; r = b; while(r < e) { c = *r++; if('(' == c || '{' == c || '[' == c) { l = r; } else if(')' == c || ']' == c || '}' == c) { m = 0; while(l > b && '(' != m && '[' != m && '{' != m) { m = *--l; } if(((m & 1) + 1 + m) != c) { return(r - 1); } if(l <= b) { b = r; l = b; } } } m = 0; while(l > b && '(' != m && '[' != m && '{' != m) { m = *--l; } return(m ? l : NULL); }
After thinking about this approach for a while, I realized that it will not work as it is now.
The problem will be that if you have "[() ()]", it will not succeed when reaching "]".
But instead of deleting the proposed solution, I will leave it here, since it is actually not impossible to make it work, but it requires some modification.
user1985657 Feb 13 '13 at 19:31 2013-02-13 19:31
source share