OK, conceptually, it’s quite easy. A couple of my friends got asked this question when interviewing. Here are what my solutions are:

1. The trivial way

This is the probably the most trivial version:

public string Reverse1(string s)
{
char[] c = s.ToCharArray();
string ts = string.Empty;

for (int i = c.Length 1; i >= 0; i–)
ts += c[i].ToString();

return ts;
}

2. Using a stack

This method is essentially the same as the first one, however it uses the FILO nature of the stack to accomplish the same task.

public string Reverse(string s)
{
Stack<string> stack = new Stack<string>();

for (int i = 0; i < s.Length; i++)
stack.Push(s.Substring(i, 1));

string ts = string.Empty;
for (int i = 0; i < s.Length; i++)
ts += stack.Pop();

return ts;
}

3. Using recursion (The cool way)

This version is probably the coolest and might just be what your interviewer was looking for. It actually does not need extra storage (it uses the stack but you do not need to programmatically allocate space in your code like the previous two cases).

Here’s the how you would use the Reverse method:

public string Reverse(string s, int l)
{
if (l == 1)
return s;
else
return Reverse(s.Substring(1, s.Length 1), –l) + s[0].ToString();
}

Here’s the how you would use the Reverse method:

string s = “ABCDEFGHIJK”;
Console.WriteLine(Reverse(s, s.Length));

Be Sociable, Share!