I made a function which checks if a word is the opposite of each other (ex: word and drow) and then realized that with minor changes it could also be used to detect if a word is palindrome. They both return bools, false means they aren't opposite/it isn't palindrome, true means they are/it is. First function:
bool opposite(std::string& first, std::string& second) {
size_t size = first.size();
if (size != second.size()) {
return false;
}
for (size_t left = 0, right = size - 1; first[left] == second[right]; ++left, --right) {
if (left == size) {
return true;
}
}
return false;
}
Second function:
bool palindrome(std::string& word) {
for (int left = 0, right = word.size() - 1; word[left] == word[right]; ++left, --right) {
if (right < 0) {
return true;
}
}
return false;
}
In the second function I decided to use int because size_t is unsigned, I could use left == first.size()
in the if statement, but that would mean calling size() twice which I think would slow me down. The other option would be storing the value returned by first.size()
in a size_t (let's call it size), using it to initialize right and changing the condition to left == size
, but that would mean keeping an extra size_t variable around.
I already tested them, they work, but the question is, are there improvements I can make to speed them up?