What is wrong in this?
#include<bits/stdc .h>
using namespace std;
bool isPalindrome(string str)
{
char temp[1000];
int len=str.length();
int i=0;
while(len)
{
len--;
temp[i ]=str[len];
}
temp[i]='\0';
if (strcmp(str,temp)==0)
return true;
else
return false;
}
CodePudding user response:
Here's how you do it:
#include <string_view>
#include <algorithm>
bool isPalindrome(std::string_view const str) {
return std::equal(str.begin(), str.begin() str.size() / 2, str.rbegin());
}
Highlights:
std::equal
std::string_view
std::string_view::rbegin
CodePudding user response:
Your code is far more complex than it should be.
bool isPalindrome(const string& str) {
int i = 0, j = str.size() - 1;
while (i < j) {
if (str[i] != str[j]) return false;
i , --j;
}
return true;
}
Another implementation:
bool isPalindrome(const string& str) {
for (int i = 0; i < str.size() / 2; i )
if (str[i] != str[str.size() - i - 1])
return false;
return true;
}
strcmp()
function that you are using, accepts only c-string as arguments, but you are passing C string. Also it won't work if string str
length is more than 1000.