确定字符串是否为回文而不改变输入

时间:2014-02-02 04:11:13

标签: c++ pointers palindrome

我正在尝试用C ++编写一个程序,它将字符串作为标准cin输入的输入,并确定输入是否为回文。我无法以任何方式更改字符串,我无法复制它。

代码必须包含bool isPalindrome( const char* x){}

之类的内容

我的尝试列在下面。

#include <cctype>
#include <iostream>
#include <string>

using namespace std;

bool isPalindrome( const char* x)
{
  string str = *x;
  int n = str.length();
  for (int i = 0; i < n; ++i)
  {
    int j = 0;
    while (isalpha(str[i]))
    {
      if (isalpha(str[n-j-1])) 
      {
        if (tolower(str[i]) == tolower(str[n-j-1]))
          return true;
        else
          return false;
      }
      j +=  1;
    }
  }
  return true;
}

int main()
{
  string str;
  cout << "Enter your string: ";
  getline (cin, str);
  const char * x ;
  x = &str;
  if (isPalindrome(x) == true)
  {
    cout << "Yes it is!" << endl;
  }
  else
  {
    cout << "No, it's not." << endl;
  }
  cout << str << endl;
  return 0;
}

我不是最好的c ++程序员,指针的使用对我来说仍然有点混乱。参数const char * x是否意味着输入被初始化为指针值是否恒定?任何帮助是极大的赞赏!

编辑:我忘了提及......输入可能包含标点符号,但仍然可以是回文。例如“女士,我是亚当!”是一个回文。但我不能从字符串中删除标点符号,因为不允许更改字符串。

4 个答案:

答案 0 :(得分:4)

尝试这种方式:

bool isPalindrome(const string& s)
{
    int a = 0;
    int b = s.size()-1;
    while(a<b)
    {
        if(s[a] != s[b]) return false;
        ++a;
        --b;
    }
    return true;
}

编辑:关于你的第二个问题:
const char * x是指向数组的指针,其中元素为const
char * x是指向数组的指针,
char * const x是指向数组的const指针,
const char * const x是指向数组的const指针,其中元素为const

<强> EDIT2: 看起来你的代码中几乎已经有了它,但是你的true太快了after you find a single character match。但是,当您已经使用C ++ char *时,请不要使用string。如果只使用string对象,则可以使代码更清晰。

以下是我如何有效地跳过非字母字符:

bool isPalindrome(const string& s)
{
    int a = -1; // points before the first character
    int b = s.size(); // points after the last character
    for(;;)
    {
        // in each iteration shift `a` and `b` at least by one
        do ++a; while(a<b && !isalpha(s[a]));
        do --b; while(a<b && !isalpha(s[b]));

        if(a >= b) return true;
        if(toupper(s[a]) != toupper(s[b])) return false;
    }
}

或者效率不高但可能更难制作错误(哦,但是它会复制字符串而你不想要那个):

#include <algorithm>

bool badchar(char c)
{
    return !isalpha(c);
}

bool isPalindrome2(const string& s)
{
    string copy(s);
    transform(s.begin(), s.end(), copy.begin(), ::toupper);
    copy.erase(remove_if(copy.begin(), copy.end(), badchar), copy.end());
    string rev = copy;
    reverse(rev.begin(), rev.end());
    return copy == rev;
}

我更喜欢第一种方式。

答案 1 :(得分:2)

逻辑很简单。将字符串从中间分开。首先比较,依此类推至中间。如果字符在任何点都不相等,那么它不是回文。

代码段(未经测试):

char string[] = "level";
int length;

length = strlen(string);

for(int i = 0, j = length - 1; i < (length / 2) ; i++, j--) {
    if(string[i] != string[j]) {
        // Not palindrome
        return false;
    }
}

答案 2 :(得分:0)

你在第一个角色后面就回来了,所以其余的都不会随时进行比较

if (tolower(str[i]) == tolower(str[n-j-1]))
    return true;
else
    return false;

只有在有任何差异时才返回,否则等到所有字符都被比较后

答案 3 :(得分:-1)

如果您使用的是C ++,请使用 vector 。首先将字符串插入向量,反转向量,然后检查原始向量,反向向量是否相等。如果相等,则回文不然。

您不需要任何指针。简单。 :)

相关问题