Pages

Tuesday, February 1, 2011

Recursive Approach for Reversing a String


Recursive Approach for Reversing a String

Simple Approach: Take the last character + reverse(rest of the string)
Base Case: When we encounter a single character, return that character.

string reverse(string str) {
if (str.length()==1)
return str;
return str[str.length()-1]+reverse(str.substr(0,str.length()-1));
}

No comments:

Post a Comment