c++ - 在不更改输入的情况下确定字符串是否为回文

标签 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 是否意味着输入被初始化为值恒定的指针?任何帮助是极大的赞赏!

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

最佳答案

试试这个方法:

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

编辑2: 看起来您的代码中几乎已经包含了它,但您返回 true 的速度太快了,after you find a single character match 。但是,当您已经使用 C++ string 时,请勿使用 char *。如果只使用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;
}

我更喜欢第一种方式。

关于c++ - 在不更改输入的情况下确定字符串是否为回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21506927/

相关文章:

c++ - 编译器能否正确处理静态变量的初始化顺序?

c++ - 计算代码行数

c - 字符 : different output when run vs. 的字母顺序已调试?

algorithm - Manacher 算法(在线性时间内找到最长回文子串的算法)

c++ - 为什么非常大的 If 语句会导致堆栈溢出

c - 在C中的地址位置存储一个字符

c++ - 是否有可能在 C++ 中的 std::vector<char> 中获取连续内存片段的指针?

c++ - 只删除一个元素使字符串回文

c - linux回文字符串参数

c++ - 派生类模板化时访问基本成员数据错误