检查字符串是否为回文。 C++

发布于 2025-01-31 10:53:08 字数 323 浏览 3 评论 0原文

这有什么问题?

#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;
 }

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;
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枫以 2025-02-07 10:53:08

如下所示:

#include <string_view>
#include <algorithm>

bool isPalindrome(std::string_view const str) {
    return std::equal(str.begin(), str.begin() + str.size() / 2, str.rbegin());
}

亮点:

std ::等等
std :: string_view

<

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

老娘不死你永远是小三 2025-02-07 10:53:08

您的代码远比应有的要复杂得多。

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;
}

另一个实现:

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()您正在使用的功能,仅接受C-string作为参数,但是您正在传递C ++字符串。同样,如果字符串str长度大于1000,则它将无法使用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文