I was implementing different versions of a recursive function that checks whether a string is a palindrome and calculating complexities for them, but was confused about passing the string size as a parameter or calculating it using size()
function and store it in a variable created inside the function, which would be more efficient?
Here's an Example of the 2 versions of the function:
bool isPalindrome1 (string s) {
int sz = s.size(); // size calculated and stored
if (sz < 2) return true;
return ((s[0] == s[sz-1]) && isPalindrome1(s.substr(1, sz-2)));
}
and,
bool isPalindrome2 (string s, int sz) { //size passed as parameter
if (sz < 2) return true;
return ((s[0] == s[sz-1]) && isPalindrome2(s.substr(1, sz-2), sz-2));
}
The first function would obviously take more time "time needed for size()
function to return the size" but would this be of a significant delay if the original string size was kinda large? how's the complexity here calculated?
Note: I know this isn't the most efficient way to check recursively if a string is a palindrome, I'm just trying to better understand complexity and recursion.