Friday, April 18, 2008

Stack vs Recursion

When reading about stacks or recursion, I found lots of people saying that recursion can be simulated using stacks. I knew this was true but never actually tried to convert a recursive code to one using stacks before, well, until today. I found this problem talking about a language that has some kind of regular expression, they gave you the language rules and you them will be given a sentence to check if it's valid or not. First of all, I wrote a recursive code. It was the first thing I thought of, then, having received Wrong Answer for that, I decided to code it again from scratch. I then had the idea of making it using stacks as a replacement of the recursive function. The main idea was something like: having a string of letters push them all in the stack until you find a combination of letters that can be replaced by other simpler combination of letters, so replace them and continue doing this process until you can't make it any simpler. The code looks something like:

//s & s2 are stacks, str is a string
s = Sentence(str);
temp = ToString(s);
s2 = Sentence(temp);
while(s != s2)//can't make the sentence any simpler
{
s = s2;
temp = ToString(s);
s2 = Sentence(temp);
}

The code in Sentence() iterates on the string str passed to it (and oush it in the stack) and whenever it encounters a combination that can get simpler it just pop it from the stack and push the simpler equivalent one. Then back to the main(), I convert it to string to process on it again. I just discovered that I can do so without using a stack and by just using a string. It will save the time of ToString() function, but for me, it's more understandable this way.


That's if for this time. Hope I come back latter with something useful. Here are the problem links in the old and new servers, and in case they just invented a new server it's problem number 271 :D

No comments: