C++编码逻辑 - 各种想法

发布于 2024-09-07 22:02:07 字数 229 浏览 3 评论 0原文

我想编写一个方法来确定给定的字符串是否是回文。例如“女士,我是亚当”,或“一个男人,一个计划,一条运河,巴拿马”。

该函数的原型是:

bool is_palindrome(char const * str)

我有一个简单的逻辑,通过前进和后退来检查是否相等。从弦的最末端向后。但是,我想知道有多少种有效的方法可以做到这一点?欢迎来自 C++ 专家的所有想法..

I want to write a method to determine if a given string is a palindrome. E.g. "Madam I'm Adam", or "A man, a plan, a canal, Panama".

The prototype for the function is:

bool is_palindrome(char const * str)

I have a simple logic to check for equality by moving forward & backward from extreme ends of the string. But, i would like to know how many efficient ways to do this ? All ideas welcome from C++ gurus..

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

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

发布评论

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

评论(1

沩ん囻菔务 2024-09-14 22:02:07

我认为没有更有效的方法,您必须比较字符串中的每个字符。

可能的优化:只需检查字符串的前半部分,一旦发现不匹配就可以尽早突破。

bool is_palindrome(char const * str) 
{
    size_t len = strlen(str);
    bool isPalindrome = false;    // It's debatable if a blank string is a palindrome or not

    for(int i = 0; i < len / 2; i++)
    {
        if(str[i] != str[len - i - 1])
        {
            isPalindrome = false;
            break;
        }
        isPalindrome = true;
    }

    return isPalindrome;
}

I don't think there is a much more efficient way, you do have to compare every character in the string.

Possible optimisations: You only have to check the first half of the string, and you can break out early as soon as you find a mismatch.

bool is_palindrome(char const * str) 
{
    size_t len = strlen(str);
    bool isPalindrome = false;    // It's debatable if a blank string is a palindrome or not

    for(int i = 0; i < len / 2; i++)
    {
        if(str[i] != str[len - i - 1])
        {
            isPalindrome = false;
            break;
        }
        isPalindrome = true;
    }

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